PHP& SQL Photo Gallery占位符图像

时间:2015-10-24 18:00:46

标签: php mysql

我有一个名为RandomPic()的函数,它将显示数据库中的随机照片。现在我想要一个空的Gallerys类别的占位符图像。但我的代码不起作用。它没有显示占位符图像....任何想法?这是代码:

$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;
}

1 个答案:

答案 0 :(得分:0)

略微更改代码结构:

$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。{/ li>中检查这一点是没有意义的
  • 不需要while,因为您的查询只能返回0或1个结果。如果您确实要返回多张图片,可以附加到$imglos

    while ( $row = mysqli_fetch_array($result) )
         $imglos .= '<img class="img-responsive" src="http://www.anyurl.com'.$row["filename"].'">';
    
相关问题