所以我有这个从数据库中取出视频的代码,一切正常,但是当结果为空时显示错误(如果没有与电影名称匹配的视频,则显示Warning: Invalid argument supplied for foreach()
)我想要做的是,如果没有与电影名称匹配的视频,那么显示echo没有视频。我的代码:
function fetchvideo($mtitle=NULL)
{
if($mtitle!=NULL) {
$column = "moviename";
$data = $mtitle;
}
global $mysqli;
$video= $mysqli->prepare("SELECT vid,image,title,moviename FROM movie_videos WHERE $column = ?");
$video->bind_param('s', $data);
$video->execute();
$video->bind_result($vid,$vimage,$vtitle,$moviename);
while ($video->fetch()){
$row[] = array('vid' => $vid, 'image' => $vimage, 'title' => $vtitle, 'moviename' => $moviename);
}
$video->close();
return ($row);
}
答案 0 :(得分:2)
未显示抛出错误的代码,因为未显示foreach
。但是,通过在上述函数中添加一行就可以轻松解决这个问题:
function fetchvideo($mtitle=NULL)
{
if($mtitle!=NULL) {
$column = "moviename";
$data = $mtitle;
}
global $mysqli;
$video= $mysqli->prepare("SELECT vid,image,title,moviename FROM movie_videos WHERE $column = ?");
$video->bind_param('s', $data);
$video->execute();
$video->bind_result($vid,$vimage,$vtitle,$moviename);
$row = array();
while ($video->fetch()){
$row[] = array('vid' => $vid, 'image' => $vimage, 'title' => $vtitle, 'moviename' => $moviename);
}
$video->close();
return ($row);
}
通过添加$row
声明,确保始终返回数组,如果没有找到视频则将其设置为空。然后,您可以在执行foreach循环之前检查是否存在视频,如果没有可用的视频,则显示相应的消息:
if (!empty($row)) {
foreach ($row as $video) {
// Show video
}
} else {
echo 'No videos';
}