douqiang5933 2012-10-20 09:21
浏览 14
已采纳

从具有特定ID的db中检索所有帖子

I'm want to retrieve all posts with a certain listId from the database, but only retrieves the last one. Below is the code, what am I doing wrong?

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

from 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
}

The tables

listElement: listElemId, listElemName, listId, listElemDescId, listElemOrderPlace

listElemDesc: listElemDescId, listElemId, listElemDesc

  • 写回答

1条回答 默认 最新

  • dstk51319 2012-10-20 09:39
    关注

    You are overwriting $listElements variable on each iteration, to fix it you can use an array variable:

    $listElements = array();
    while ($stmt->fetch()) {
        $listElements[] = array('listElemId' => $listElemId,     //notice brackets: []
                             'listElemName' => $listElemName,
                             'listElemOrderPlace' => $listElemOrderPlace,
                             'listElemDesc' => $listElemDesc);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分