PHP: why can't I loop twice on mysqli_fetch_array() results? [duplicate]

空扰寡人 提交于 2019-12-29 02:12:08

问题


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.


回答1:


From PHP's mysqli_fetch_array DOCS:

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.

You are using a 'while' loop on $row = mysqli_fetch_array($newsQuery)

This means the loop will keep going untill mysqli_fetch_array($newsQuery) returns 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"];
}



回答2:


While it is best to avoid logic that results in looping through a result set twice, if necessary you need to reset the result set back to the start:-

mysqli_data_seek($newsQuery, 0);



回答3:


Because you already fetch the value of $newsQuery Try this code

//temporary save the news content into array
$content = array();
$x=0;
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>";
 $content[$x]= $row["news_content"];
 $x++;
}

and if you want to retrieve it

//now retrieve it
for($y=0; $y<count($content); $y++)
{
 echo $content[$y]+"<br/>";

}


来源:https://stackoverflow.com/questions/26482625/php-why-cant-i-loop-twice-on-mysqli-fetch-array-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!