开发者

Query data from one table based on id from another

开发者 https://www.devze.com 2023-04-04 01:53 出处:网络
I\'m new to php. I have one table with users and another with email addresses and user id\'s they are associated with. I\'d like to list all of the email addresses by user id. I think I need some nest

I'm new to php. I have one table with users and another with email addresses and user id's they are associated with. I'd like to list all of the email addresses by user id. I think I need some nested while loops, but not sure how to do it... Any help is appreciated.

$rows = mysql_num_rows(mysql_query("SELECT * FROM users"));
$data = 开发者_运维百科mysql_fetch_array(mysql_query("SELECT * FROM users"));

$i==0;
while ($i < $rows){
  $.... this is where i'm lost
}

Thanks


There are better ways to do it, perhaps like this:

$query = mysql_query("SELECT * FROM users");
// Loop through the users
while ($row = mysql_fetch_array($query) {
  $query2 = mysql_query('SELECT * FROM emails WHERE user_id = ' . $row['id']);
  // Loop through this user's email addresses
  while ($row2 = mysql_fetch_array($query2) {
    // Build up a string/array for your output with the email addresses in $row2['field_name']
  }
}

You could also use a MySQL JOIN to get all the data from the database at once and not run multiple queries.

Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消