Jump to content

double while loop question


mraza

Recommended Posts

Hi i am in a situation where i need to use two tables. please look at my code

 

$result= $db->dbrun('select * from table_user');
while($row = mysql_fetch_array($result)): 
echo $row['username'] . '<br />';
endwhile;

now my problem is i wants to get something from other table where user id match with $row['id'],

 

$result= $db->dbrun('select * from table_user');
while($row = mysql_fetch_array($result)): 
$query= $db->dbrun('select id from table_other where user_id =$row['id']');
while($user_row = mysql_fetch_array($query)): 
echo $row['username'] . ' - ' . $user_row['id'] . '<br />';
endwhile;
endwhile;

 

so my main question is is it ok to run $query within  a while loop because i cant run this query without $row['id'] which i gets after loop started or is there any other good way.

 

Thanks for answering.

 

Link to comment
Share on other sites

You can use a MySQL JOIN query instead of the nested while loops. Something like this would be the equivalent for your example:

 

SELECT table_user.*, table_other.id FROM table_user JOIN ON (table_user.id = table_other.user_id)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.