【问题标题】:Retrieving all posts from db with a certrain id从 db 中检索具有特定 id 的所有帖子
【发布时间】:2012-10-20 09:21:06
【问题描述】:

我想从数据库中检索具有特定 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;
}

来自database.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

【问题讨论】:

  • 使用 sqlfiddle 会容易得多...

标签: php mysql sql database mysqli


【解决方案1】:

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

$listElements = array();
while ($stmt->fetch()) {
    $listElements[] = array('listElemId' => $listElemId,     //notice brackets: []
                         'listElemName' => $listElemName,
                         'listElemOrderPlace' => $listElemOrderPlace,
                         'listElemDesc' => $listElemDesc);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2021-09-23
    • 1970-01-01
    相关资源
    最近更新 更多