使用新的 mysqli 查询获取多行


fetching multiple rows with new mysqli query?

我正在使用php连接到mysql数据库,并使用以下函数从数据库中检索多行,然后将它们添加到数组中并将它们发回。我收到内部服务器错误或 500x 错误消息。我不确定这段代码有什么问题。我试图弄清楚,但无法得到它。

public function getUnreadMessages($uname){
          $stmt = $this->conn->prepare("SELECT msgid, title, fromuname FROM messages WHERE touname = ? and status = ?");
          $status = 'unread';
        $stmt->bind_param("ss", $uname, $status);
        if ($stmt->execute()) {
                $stmt->bind_result($col1, $col2, $col3);
                $stmt->store_result();
                $resp = array();
            while($stmt->fetch()){
                        $row = array();
                        array_push($row, $col1, $col2, $col3);
                        array_push($resp, $row);            
            }
            $msg = array('msgid' => $msgid,'title' => $title,'fromuname' => $fromuname);
            $stmt->close();
            return $msg;
        } else {
                        $stmt->close();
                     return NULL;
        }
    }

我应该怎么做?处理返回结果的函数如下

$app->get('/inbox', 'authenticate', function() use ($app){
        ob_start("ob_gzhandler");
        global $global_user_name;
        $db = new DbHandler();
        $resp = $db->getUnreadMessages($global_user_name);
        $msgs = array();
        $msgs['status'] = 'success';
        $msgs['version'] = 0.1;
        array_push($msgs, $resp);
        $app->response()->header('Content-Type', 'application/json');
        echo json_encode($msgs);
        exit;
});

自动执行此操作的PDO方法是$stmt->fetchAll():D

public function getUnreadMessages($uname)
{
    $stmt = $this->conn->prepare("SELECT msgid,title,fromuname FROM messages WHERE touname = ? and status = ?");
    $stmt->execute([$uname, 'unread']))
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

如果未找到任何内容或类似以下内容,则返回false

$msg = [
    [
        'msgid' => 2746,
        'title' => 'Random title',
        'fromuname' => 'SomeGuy'
    ],
    [
        'msgid' => 754,
        'title' => 'Some title',
        'fromuname' => 'Random Name'
    ],
    [
        'msgid' => 27686,
        'title' => 'Unreadable title',
        'fromuname' => 'Training dummies'
    ],
];

我已经解决了我的问题。而是我在循环中创建了一个数组。这似乎是不允许的。这是最终确实有效的代码

public function getUnreadMessages($uname){
            $stmt = $this->conn->prepare("SELECT msgid, title, fromuname FROM messages WHERE touname = ? and status = ?");
                $status = 'unread';
                $stmt->bind_param("ss", $uname, $status);
            $result = $stmt->execute();
            $stmt->bind_result($col1, $col2, $col3);
            $stmt->store_result();
            $outer = array();
            $inner = array();
            while($stmt->fetch()){
                    array_push($inner, $col1, $col2, $col3);
            }
            array_push($outer, $inner);
            return $outer;
            $stmt->close();
    }