我想从数据库中检索具有某个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
答案 0 :(得分:2)
你在每次迭代时覆盖$ listElements变量,修复它你可以使用数组变量:
$listElements = array();
while ($stmt->fetch()) {
$listElements[] = array('listElemId' => $listElemId, //notice brackets: []
'listElemName' => $listElemName,
'listElemOrderPlace' => $listElemOrderPlace,
'listElemDesc' => $listElemDesc);