循环通过mysqli结果

时间:2013-07-31 23:21:57

标签: php mysqli

我正在尝试显示已登录用户关注的艺术家的状态更新列表。

到目前为止,我有这个:

#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)

}

但我不知道如何循环并显示返回的状态更新?

这不是我的强项,所以任何指针都会非常感激!

2 个答案:

答案 0 :(得分:3)

是什么阻止了您执行类似于第一次查询的操作?如下所示:

#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
  }
}

或者如果这两个表artist_likesstatus_updates共有artist_id,那么您可以使用一个带有连接的查询。 (但不知道你是否要求这样做。)

答案 1 :(得分:0)

为避免多次查询,您可以使用以下一个查询:

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

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