简体   繁体   中英

Looping through a mysqli result

I'm trying to display a list of status updates from artists that a logged in user is following.

So far I have this:

#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {

  #Now grab the statuses for each artist
  $status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
  $status_result = mysqli_query($dbc,$status_query)

}

But i'm not sure how to loop through and display the returned status updates?

This isn't a strong point of mine, so any pointers would be greatly appreciated!

What prevented you from doing similar to what you'd already done for the first query? Something like follows:

#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {

  #Now grab the statuses for each artist
  $status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
  $status_result = mysqli_query($dbc,$status_query)

  while($status_result_row = mysqli_fetch_assoc($status_result)) {
    echo $status_result_row['mycol']; // This is where you know better than us
  }
}

Or if those two tables artist_likes and status_updates have artist_id in common then you could just use one query with a join. (But don't know if you are asking for that).

Just for avoiding multiple query, you can use one query like this:

SELECT l.*, s.* 
from artist_likes l, status_updates s
WHERE
l.artist_id = s.artist_id and
l.user_id = '1'

or

SELECT l.*, s.* 
from artist_likes l
JOIN status_updates s on (l.artist_id = s.artist_id)
WHERE
l.user_id = '1'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM