开发者

MySQL query within another query's while loop in PHP

I have the following code:

$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($result = mysql_fetch_array($query)) {
    extract($result);
    if ($activity_type == "discussion") {

        $query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
        while($result = mysql_fetch_array($query)) 开发者_JAVA技巧{
            extract($result);
            echo $discussion_user . " said:<br>" . $discussion_text . "<br>";
        }

    } elseif ($activity_type == "file") {

    }
}

But it just returns the last row. My goal is to have a chronological list of "activities" each displayed slightly differently depending on their type.


Your using $query and $result twice so the second loop is overwriting the result of the first and stopping...

$query = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");

and

$query = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");

same with $results var...

I would suggest you change to $query and $query2 but best to use something like

$activies = mysql_query("SELECT * FROM activity ORDER BY activity_time DESC LIMIT 50");
while($activity = mysql_fetch_array($activies)) {

and

$discussions = mysql_query("SELECT * FROM discussions WHERE discussion_uuid = '$activity_ref'");
while($discussion = mysql_fetch_array($discussions)) {

I would also avoid using extract - as you might be overwriting vars your not expecting to...


You have to create another connection to the database so that you can run them at the same time.

OR

You can load the results of the first one into an array, and then just loop through the array.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜