开发者

Web page not loading with PHP-MySQL code while outputting JSON

开发者 https://www.devze.com 2023-03-11 04:50 出处:网络
I am using the code below to get information from a database and make it into JSON (it may be wrong).

I am using the code below to get information from a database and make it into JSON (it may be wrong).

Unfortunately it won't load 开发者_运维百科in my web browser, it just says it's loading but it doesn't finish. Please can you tell me what I am doing wrong.

$query = mysql_query("SELECT * FROM Posts ORDER BY date DESC") or die(mysql_error());
$array = array(); 
while ($row = mysql_fetch_assoc($query)) { 
$array[] = $row; 
$postID =     $row['id']; 
while ($ra = mysql_fetch_assoc(mysql_query("SELECT * FROM Comments WHERE postID = '$postID'"))) { 
$array['comments'] = $ra; 
} 
while ($rd = mysql_fetch_assoc(mysql_query("SELECT * FROM Likes WHERE postID = '$postID'"))) { 
$array['likes'] = $rd;
 } 
} 
echo json_encode($array);


You are executing mysql_query in the infinite loop: on each iteration you query the database, and fetch the first row. Change it to

$res = mysql_query("SELECT * FROM Comments WHERE postID = '$postID'");
if (!$res)
{
   // handle error
}
while ($ra = mysql_fetch_assoc($res)) 
{
 ....
}

And the same for your second query.

0

精彩评论

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