0

我想从数据库中检索具有特定 listId 的所有帖子,但只检索最后一个。下面是代码,我做错了什么?

来自 listModel.php:

public function GetListElements($listId) {

    $query = "SELECT le.listElemId, le.listElemName, le.listElemOrderPlace, led.listElemDesc
                FROM listElement AS le
                INNER JOIN listElemDesc as led
                ON le.listElemId = led.listElemId
                WHERE le.listId=?";

    $stmt = $this->m_db->Prepare($query);

    $stmt->bind_param("i", $listId);

    $listElements = $this->m_db->GetListElements($stmt);

    return $listElements;
}

从数据库.php:

public function GetListElements(\mysqli_stmt $stmt) {

    if ($stmt === FALSE) {
            throw new \Exception($this->mysqli->error);
    }

    //execute the statement
    if ($stmt->execute() == FALSE) {
            throw new \Exception($this->mysqli->error);
    }

    //Bind the $ret parameter so when we call fetch it gets its value
    if ($stmt->bind_result($listElemId, $listElemName, $listElemOrderPlace, $listElemDesc) == FALSE) {
        throw new \Exception($this->mysqli->error);
    }

    // Hämtar ids och användarnamn och lägger i arrayen.
    while ($stmt->fetch()) {
        $listElements = array('listElemId' => $listElemId,
                             'listElemName' => $listElemName,
                             'listElemOrderPlace' => $listElemOrderPlace,
                             'listElemDesc' => $listElemDesc);
    }

    $stmt->Close();

    return $listElements;    // contains only the last post in the table
}

桌子

listElement: listElemId、listElemName、listId、listElemDescId、listElemOrderPlace

listElemDesc: listElemDescId,listElemId,listElemDesc

4

1 回答 1

2

在每次迭代时覆盖 $listElements 变量,要修复它,您可以使用数组变量:

$listElements = array();
while ($stmt->fetch()) {
    $listElements[] = array('listElemId' => $listElemId,     //notice brackets: []
                         'listElemName' => $listElemName,
                         'listElemOrderPlace' => $listElemOrderPlace,
                         'listElemDesc' => $listElemDesc);
于 2012-10-20T09:39:26.167 回答