php - 如何从 php 函数返回 db 查询的结果?
问题描述
我正在尝试将我的数据库代码放入一个函数中。我无法从函数返回结果,因此页面上的所有变量都抛出未定义的变量错误。
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;
}
我在这里做错了什么?
解决方案
要创建数组数组:
$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;
推荐阅读
- python - 如何使用 python selenium 获取 div 文本?
- python - 熊猫。将数据框中具有相同值的所有列合并为单个列
- html - 导航栏背景颜色
- c# - 使用 BouncyCastle SHA-256withPLAIN-ECDSA 的确定性签名
- c# - 可能的空引用分配警告对我来说似乎是假的
- node.js - Sophos 干扰 Mac OSX Big Sur 上的 NodeJS 进程
- python - 使用嵌套元组在列上应用多个过滤器
- c++ - 有效地遍历数据库行(libpqxx),将值分配给结构
- compare - 对两个类别中的行进行排名和选择
- reactjs - 禁用自动填充 React-Material UI-FormGroup 登录表单中的字段的选项