0

I have two simple tables T1 and T2 both of datas coming by uploading. I want to display the file_name under a specific user_id.

T1
-------------------------
ID    user_id  admin_id
1     5        11
2     6        11
3     5        11


T2
--------------------------
ID    user_id  file_name 
1     5        orange
2     6        apple
3     5        banana

My problem is it would display twice the echo as below, instead of only once. What is the best way to do this? Do I have to use inner join? Or is it possible to use only 2 for each loop. Sorry for a noob question.

orange banana

orange banana

Here is my sample:

$test1 = select user_id,admin_id FROM T1;

for($test1 as $key => $value)
{
  $test2 = select user_id,file_type FROM T2;

  foreach($test2 as $key => value2)
  {
    if(test1->user_id==test2->user_id)
    {
      $test2 = select user_id,file_name FROM T2;
      echo $test2->file_name.'<br>';
    }
  }

}
2
  • You're talking about sql queries, but you don't seem to execute any sql in your examples. The question is tagged PHP, but the your code example isn't valid PHP. Can you be clearer and fix these problems? Commented Jul 13, 2015 at 11:22
  • yes you need joins for that.. its not a good practice to use a query inside a loop. you are only exhausting your server Commented Jul 13, 2015 at 11:22

1 Answer 1

1

First, you totally missed the php syntax in your sample (talking about the query strings), secondly there isn't any request to your mysql (or whatever sql) server.

For your SQL command you should read about the JOIN command that exists in SQL http://www.w3schools.com/sql/sql_join.asp Here is a good site to start with it. Its detailed and provides good examples

For your question about inner join: no you need left join (correct me if im wrong) and join on user_id. I won't use 2 queries + loops cause the connection is the slowest thing in a whole database transaction. The command itself will be done in about no time

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.