問題描述
我正在從 mysql 數據庫中檢索一些數據.有兩個循環使用相同的結果集.
I'm retrieving some data from a mysql database. There are two loops which uses the same result set.
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
這個循環以成功結束.然后在同一頁面中,我有以下循環.
This loop ends with success. then in the same page I have the following loop.
while ($row = mysqli_fetch_array($newsQuery)) {
echo $row["news_content"];
}
即使表中有內容,此循環也不會返回任何內容.當我在第一個循環中嘗試時.內容顯示正確.知道我做錯了什么.
This loop doesn't return anything even if there are content in the table. When I try it in the first loop. the content is displayed correctly. Any idea on what I'm doing wrong.
推薦答案
來自 PHP 的 mysqli_fetch_array DOCS:
From PHP's mysqli_fetch_array DOCS:
返回一個與獲取的行相對應的數組,如果 result 參數表示的結果集沒有更多行,則返回 NULL.
Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
您在 $row = mysqli_fetch_array($newsQuery)
這意味著循環將繼續進行,直到 mysqli_fetch_array($newsQuery)
返回 NULL
.
This means the loop will keep going untill mysqli_fetch_array($newsQuery)
returns NULL
.
這就是您不能再次使用該循環的原因,因為 mysqli 已完成獲取結果并且 mysqli_fetch_array($newsQuery)
現在返回 NULL 直到您進行新查詢.
This is the reason why you cant use that loop again, since mysqli has finished fetching the results and the mysqli_fetch_array($newsQuery)
now returns NULL untill you make a new query.
嘗試先用結果填充一個變量,然后在該變量上循環:
Try populating a variable with the results first, then loop on that variable:
$results = array();
while ($row = mysqli_fetch_array($newsQuery)) {
$results[] = $row;
}
foreach ($results as $key => $row) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
foreach ($results as $key => $row) {
echo $row["news_content"];
}
這篇關于PHP:為什么我不能在 mysqli_fetch_array() 結果上循環兩次?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!