PHP:为什么我不能在 mysqli_fetch_array() 结果上循环两次? [英] PHP: why can't I loop twice on mysqli_fetch_array() results?

查看:41
本文介绍了PHP:为什么我不能在 mysqli_fetch_array() 结果上循环两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 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() 结果上循环两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆