在 PHP 函数中使用循环并为每一行返回数组


Using loop in PHP function and return array for each row

我目前正在创建一个接受用户 id 的函数,并且根据该 id 它应该从包含用户 id 的帖子数据库中返回所有值。我有一个单独的 php 文件,我保存了函数,因为我想在许多页面上使用它。在函数.php文件中,我有:

class getposts
{
    public function getpostcontent($userid){
    include('db-conx.php');//Connects to Db
    $getval = "SELECT `content`,`date` FROM posts WHERE userid = ?";
    $stmt = $conn->stmt_init();
    if ($stmt->prepare($getval))
    {
        $userid = $_SESSION['userid'];
        $stmt->bind_param("s", $userid);
        $stmt->execute();
        $stmt->bind_result($content, $date);
        while ($stmt->fetch()) {
            $displayname = "Tom";
            $array = [
            "content" => "$content",
            "date" => "$date",
            "displayname" => "$displayname",
            ];
            return $array;
        }
    }
}

并在帖子中使用调用它.php:

$posts = new getposts();
echo $posts ->getpostcontent($userid);

问题是用户在帖子数据库中有多行,代码只运行一次。我将如何循环它以在调用它时显示每行的值?我可能想多了,四处搜索,但似乎无法让它工作。

您可以在每次迭代时向数组插入一条新记录 - 然后返回整个数组:

    while ($stmt->fetch()) {
        $displayname = "Tom";
        $array[] = array(
        "content" => "$content",
        "date" => "$date",
        "displayname" => "$displayname"
        );
    }
    return $array;

在您的代码中,每次都会覆盖数组,并且只返回数据库中的最后一行。现在它将简单地添加到 while 循环内的数组中,然后在完成后将其全部返回。

编辑:我通常使用$result将数据从数据库中提取 - 不确定您的方法是否有效 - 但如果它不研究该:)

编辑 2:

在代码中,您现在有一个数组数组。您可以像这样调用每个元素:

echo $array[0]['content'];

这将回显第一条记录中content的内容,$array[1]['content']具有数据库中的第二行,依此类推。

编辑3:

你返回的是一个数组 - 而不是一个对象,所以你可以这样做:

$posts = new getposts();
// You make an object of the class.
$returned=$posts->getpostcontent($userid);
// Now you run the query against the userID and return the array into $returned
foeach($returned as $val)
{
    print_r($val);
    // This is showing you the structure of each array inside the main array.
    // Or you can access each bit as needed:
    echo 'The date is '.$val['date'].'<br>';
    echo 'The content is is '.$val['content'].'<br>';
}