【问题标题】:Using loop in PHP function and return array for each row在 PHP 函数中使用循环并为每一行返回数组
【发布时间】:2014-12-13 00:12:12
【问题描述】:

我目前正在创建一个接受用户 id 的函数,并基于该 id 它应该从包含用户 id 的帖子数据库中返回所有值。我有一个单独的 php 文件,我将函数保存在其中,因为我想在许多页面上使用它。在functions.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;
        }
    }
}

并在 Posts.php 中调用它:

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

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

【问题讨论】:

标签: php sql mysqli


【解决方案1】:

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

    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>';
}

【讨论】:

  • 感谢您的快速回复。我试过了,我可以确认它现在确实循环了。但是,我在调用它时确实收到“数组到字符串转换”错误。希望它不应该太难修复,谢谢我会考虑存储在 $result 变量中。再次感谢:)
  • 谢谢我如何让它从functions.php文件的类中为每个数组循环一个值
  • 不工作:(。非法字符串偏移错误。可能我的代码中有一些东西我需要查看
  • 我确实有一个错字,虽然我现在已经改正了。
  • 不幸的是仍然没有运气。我会继续研究这个。根据错误,我猜测返回的是字符串而不是数组。
猜你喜欢
  • 1970-01-01
  • 2014-04-10
  • 2015-04-22
  • 2013-03-11
  • 2018-05-17
  • 2022-08-05
  • 2016-12-29
  • 2018-03-13
  • 2019-08-26
相关资源
最近更新 更多