我正在尝试将数据库代码放入函数中。我无法从函数返回结果,因此页面上的所有变量都引发未定义的变量错误。
function fetchVideo($dblink) {
$viewkey=$_GET['viewkey'];
$sql = "SELECT * FROM videos WHERE Viewkey='".$viewkey."'";
$result = mysqli_query($dblink, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
return $key=$row["Viewkey"];
return $embed=$row["Embed"];
return $link=$row["Link"];
return $url=$row["URL"];
return $categories=explode(";", $row["Categories"]);
return $rating=$row["Rating"];
return $username=$row["User_name"];
return $title=$row["Title"];
return $tags=str_replace(";","-", explode(",", $row["Tags"]));
return $duration=intdiv($row["Duration"],60);
return $thumbnail=$row["Thumbnail"];
}
} else {echo 'No Results';}
}
上面的代码在从函数中删除并删除所有“返回”时起作用。我尝试将其作为数组并返回该数组且没有骰子:
function fetchVideo($dblink) {
$viewkey=$_GET['viewkey'];
$sql = "SELECT * FROM videos WHERE Viewkey='".$viewkey."'";
$result = mysqli_query($dblink, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$video=array (
"key"=>$row["Viewkey"],
"embed"=>$row["Embed"],
"link"=>$row["Link"],
"url"=>$row["URL"],
"categories"=>explode(";", $row["Categories"]),
"rating"=>$row["Rating"],
"username"=>$row["User_name"],
"title"=>$row["Title"],
"tags"=>str_replace(";","-", explode(",", $row["Tags"])),
"duration"=>intdiv($row["Duration"],60),
"thumbnail"=>$row["Thumbnail"]
);
}
} else {echo 'No Results';}
return $video;
}
我在做什么错了?
答案 0 :(得分:-1)
要创建一个数组数组:
$video = array() # placed outside of loop and before if statement
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
// add next row to the $video array:
$video[] = array(
"key"=>$row["Viewkey"],
etc.
);
}
} else {echo 'No Results';}
return $video;