首页 > 解决方案 > 如何从 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;
    }

我在这里做错了什么?

标签: phpmysqlfunction

解决方案


要创建数组数组:

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

推荐阅读