我觉得我知道这一点,但我很沮丧,因为我不记得具体怎么做。
在 PHP 中,我需要在无序列表中重复记录集的项目。我可以很好地重复项目,但如果记录集为空,我不希望显示任何内容。现在,如果没有记录,代码仍然显示一个空白列表项,而我只想什么都不显示。
我试过这个:
<?php do { ?>
<li><a href="#">Content Goes Here</a></li>
<?php } while (!feof($recordsetName) && $row_recordsetName = mysql_fetch_assoc($recordsetName)); ?>
我尝试通过将重复元素放在 if/else 语句中来做到这一点,如下所示:
<?php if (!feof($recordsetName)) {
echo ""; }
else do { ?>
<li><a href="#">Content Goes Here</a></li>
<?php } while ($row_recordsetName = mysql_fetch_assoc($recordsetName));
; } ?>
但这也行不通。任何信息都会有所帮助
while($row = mysql_fetch_assoc($recordsetName)) {
if($row['fieldname'] != '') {
echo '<li><a href="#">Content Goes Here</a></li>';
}
}
或者您可以检查查询是否成功...
$result = mysql_query($sql);
if($result) {
echo '<li><a href="#">Content Goes Here</a></li>';
}
或者如果它返回任何结果...
$results = mysql_fetch_assoc($recordsetName);
if(mysql_num_rows($results) > 0) {
while($row = mysql_fetch_assoc($results)) {
echo '<li><a href="#">Content Goes Here</a></li>';
}
}
此外,您确实应该使用 mysqli
或 PDO
,因为mysql
已折旧。
编辑:在示例 3 中添加了循环。