我有一个名为RandomPic()的函数,它将显示来自数据库的随机照片。现在我想要一个占位符图像的画廊类别是空的。但是我的代码不起作用。它不显示占位符图像....什么好主意吗?下面是代码:
$sql = "SELECT * FROM wp_gallery WHERE catid = $id ORDER BY RAND() LIMIT 1";
if($result = $conn->query($sql)){
while ($row = mysqli_fetch_array($result))
{
if (mysqli_num_rows($result) > 0) {$imglos = '<img class="img-responsive" src="http://www.anyurl.com'.$row["filename"].'">';}
}
}
else{$imglos = 'PLACEHOLDERIMAGE GOES HERE';}
return $imglos;
}
稍微改变一下你的代码结构:
$sql = "SELECT * FROM wp_gallery WHERE catid = $id ORDER BY RAND() LIMIT 1";
if($result = $conn->query($sql))
{
if (mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_array($result))
$imglos = '<img class="img-responsive" src="http://www.anyurl.com'.$row["filename"].'">';
}
else
$imglos = 'TEST';
return $imglos;
}
else
return "database error!";
一些注意事项:
-
mysqli_num_rows
在执行查询后永远不会改变:它返回结果集中的行数。所以在while
中检查这个是没有意义的。 不需要
while
,因为您的查询只能返回0或1个结果。如果您确实想要返回多个图像,您可以附加到$imglos
:while ( $row = mysqli_fetch_array($result) ) $imglos .= '<img class="img-responsive" src="http://www.anyurl.com'.$row["filename"].'">';