<?php
function comment($postid,$db_con)
{
$commentdiv='';
$sql="SELECT userid,time,comment FROM comments WHERE postid='$postid' LIMIT 3";
$query = mysqli_query($db_con, $sql);
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){
$uid=$row["userid"];
$timecomment=$row["time"];
$comment=$row["comment"];
$sql="SELECT username,photo FROM users WHERE id='$uid'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$username=$row["username"];
$photo=$row["photo"];
$userphoto='<img src="xxx/'.$username.'/'.$photo.'">';
if($photo== NULL){
$userphoto = '<img src="xxx/default.png">';
}
$commentdiv.='<div class="xxxxxxx"><div class="yyyyyy">'.$userphoto.'</div><div class="zzzzz">'.$username.'</div><div class="vvvvv">'.$comment.'</div></div>';
}
return $commentdiv;
}
?>
我是PHP的新手,我试图从上面的PHP代码返回3条评论,但上面的代码只返回数据库中的1行,为什么当有多于1行时,fetch数组只返回1行?
答案 0 :(得分:1)
您正在覆盖在while循环中提供结果的mysql资源变量。
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){
^^^^^^ Original resource variable
再次在while循环内部使用查询变量
$query = mysqli_query($db_conx, $sql);
^^^^^^ Overwriting $query inside the while loop
一个建议是将循环中的变量重命名为其他内容。
答案 1 :(得分:0)
尝试,我使用$query2 = mysqli_query($db_conx, $sql);
进行第二次查询,因为它会重置第一个循环
<?php
function comment($postid,$db_con)
{
$commentdiv='';
$sql="SELECT userid,time,comment FROM comments WHERE postid='$postid' LIMIT 3";
$query = mysqli_query($db_con, $sql);
while($row = mysqli_fetch_array($query,MYSQLI_ASSOC)){
$uid=$row["userid"];
$timecomment=$row["time"];
$comment=$row["comment"];
$sql="SELECT username,photo FROM users WHERE id='$uid'";
$query2 = mysqli_query($db_conx, $sql); // added new variable
$row = mysqli_fetch_array($query2,MYSQLI_ASSOC);
$username=$row["username"];
$photo=$row["photo"];
$userphoto='<img src="xxx/'.$username.'/'.$photo.'">';
if($photo== NULL){
$userphoto = '<img src="xxx/default.png">';
}
$commentdiv.='<div class="xxxxxxx"><div class="yyyyyy">'.$userphoto.'</div><div class="zzzzz">'.$username.'</div><div class="vvvvv">'.$comment.'</div></div>';
}
return $commentdiv;
}
?>