使用新的mysqli查询获取多行?

时间:2014-12-04 06:53:02

标签: php mysql rest mysqli

我正在使用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;

});

2 个答案:

答案 0 :(得分:0)

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'
    ],
];

答案 1 :(得分:0)

我已经解决了我的问题。就是我在循环中创建一个数组。这似乎是不允许的。这是最后工作的代码

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();
    }