Php While循环中的While循环
谢谢你的回答,我真的很高兴。。我编辑了代码,我想问一下,我是否编辑得很好?:-)Php While循环中的While循环,php,loops,while-loop,Php,Loops,While Loop,谢谢你的回答,我真的很高兴。。我编辑了代码,我想问一下,我是否编辑得很好?:-) $result=$sql->query(“从`topic`;中选择*”; 而($row=$result->fetch_object()) { $id=$row->id; $photo=$row->photo; $title=$row->title; $shortinfo=$row->shortinfo; 回声“ $title $shortinfo "; 您应该将第二个查询设置为$result1,因为新的查询将替换第
$result=$sql->query(“从`topic`;中选择*”;
而($row=$result->fetch_object())
{
$id=$row->id;
$photo=$row->photo;
$title=$row->title;
$shortinfo=$row->shortinfo;
回声“
$title
$shortinfo
";
您应该将第二个查询设置为$result1
,因为新的查询将替换第一个查询。这就是为什么您总是只有一个结果
$result = $sql->query("SELECT * FROM `topic` ;");
while($row = $result->fetch_object())
{
$id=$row->id;
echo '<div id="article">
<a href="';
echo '.php"><div id="article_img"><img src="';
$result1 = $sql->query("SELECT `photo` FROM `topic` WHERE id='$id' ;");
while ($row1 = $result->fetch_array()) {
echo $row1['photo'];
}
}
$result=$sql->query(“从`topic`;中选择*”;
而($row=$result->fetch_object())
{
$id=$row->id;
回声'
查询(“从`topic`中选择`photo`其中id='$id';”;
而($row1=$result->fetch_array()){
echo$row1['photo'];
}
}
$result
和$row
两个循环中使用相同的变量名。我建议使用可读且自解释的变量名,如$photo\u result
和$title\u result
。这样也可以解决您的问题,因为您在循环中使用相同的变量名
为了性能和简单性,为什么不
加入表呢?这样就只有一个查询和一个循环。始终给出正确的变量名。您的$result和$row
保存了这里的所有变量
相同的内存位置将始终更新。因此它会丢失旧的值(我们在第一年的学位/PUC第一年就学到了这一点)
这样做,
例如,当您从主题
表中提取时,选择照片
使用变量,如$topicResultForPhto和$topicPhotoRow`。对所有人都这样做
还有一个错误
您已经像SELECT*
这样调用了,并且您拥有了表中的所有字段。为什么要再次从photo
和其他像这样的字段调用,从主题中选择photo呢
$result = $sql->query("SELECT * FROM `topic` ;");
while($row = $result->fetch_object())
{
$id=$row->id;
echo '<div id="article">
<a href="';
echo '.php"><div id="article_img"><img src="';
$result1 = $sql->query("SELECT `photo` FROM `topic` WHERE id='$id' ;");
while ($row1 = $result->fetch_array()) {
echo $row1['photo'];
}
}