[英]Loop MySQLi Prepared Statement with PHP OOP
您好,我試圖每次使用fetch()函數的while循環時都使用PHP編寫的預編寫語句循環遍歷數據庫表中的所有行,這使我陷入無限循環,這是我的代碼,請幫忙
public function loadIndex() {
$conn = new Database();
$db = $conn->Connect();
$query = "
SELECT Title,Description,uploadeddate
FROM article
ORDER BY article.uploadeddate DESC LIMIT 10";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($title, $desc, $date);
$num_rows = $stmt->num_rows();
$fetch = $stmt->fetch();
$data = array(
'title' => $title,
'desc' => $desc,
'date' => $date,
'num_rows' => $num_rows,
'fetch' => $fetch
);
return $data;
}
這是用途
<?php
art = new Articles();
$index = $art->loadIndex();
$num = $index['num_rows'];
if($num != 0) {
while() {$index['fetch']} {
echo $index['title']."<br />";
echo $index['desc']."<br />";
echo $index['date']."<br />";
}
}?>
謝謝
一團糟!
暫時忘記常識性的觀點。
沒有經過測試,但可以嘗試作為10的入門版。
文章類
public function loadIndex() {
$conn = new Database();
$db = $conn->Connect();
$title = '';
$desc = '';
$date = '';
$data = array();
$query = "SELECT Title,Description,uploadeddate
FROM article
ORDER BY article.uploadeddate DESC LIMIT 10";
$stmt = $db->prepare($query);
$stmt->execute();
$stmt->bind_result($title, $desc, $date);
while ( $stmt->fetch() ) {
$data[] = array(
'title' => $title,
'desc' => $desc,
'date' => $date
);
}
return $data;
}
主代碼調用Article-> loadIndex()
<?php
art = new Articles();
$index = $art->loadIndex();
// you dont need to know how big the $index array is here
// if its empty then the foreach will just not run.
foreach ($index as $row) {
echo $row['title'] . '<br />';
echo $row['desc'] . '<br />';
echo $row['date'] . '<br />';
}
?>
在您的索引中:
While($stmt->fetch())
{
$index =count($data);
$data['title'][$index] = $title;
...
}
首先,您應該只建立一次數據庫連接,而不是在每個函數調用中進行一次。 連接后,您只需在函數內部執行查詢即可,因此無需每次都連接。
其次,導致無限循環是因為while循環中沒有條件。
所以改變這個:
while() {$index['fetch']}
至
while($index['fetch'])
謝謝阿馬爾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.