加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

PHP:为什么我不能在mysqli_fetch_array()结果上循环两次?

发布时间:2021-07-06 05:23:27 所属栏目:大数据 来源: https://www.jb51.cc
导读:参见英文答案 Mysqli query doesn’t work twice????????????????????????????????????2个 我正在从MysqL数据库中检索一些数据.有两个循环使用相同的结果集. while ($row = MysqLi_fetch_array($newsQuery)) { echo "a href='news-article.PHP?articleId=" .

参见英文答案 > Mysqli query doesn’t work twice????????????????????????????????????2个
我正在从MysqL数据库中检索一些数据.有两个循环使用相同的结果集.

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>";
}

这个循环以成功结束.然后在同一页面中我有以下循环.

while ($row = MysqLi_fetch_array($newsQuery)) {
    echo $row["news_content"];
}

即使表中有内容,此循环也不会返回任何内容.当我在第一个循环中尝试它.内容显示正确.关于我做错了什么的任何想法.

解决方法:

来自PHP的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.

你在$row = MysqLi_fetch_array($newsQuery)上使用’while’循环

这意味着循环将一直持续到MysqLi_fetch_array($newsQuery)返回NULL.

这就是为什么你不能再次使用该循环的原因,因为MysqLi已经完成获取结果并且MysqLi_fetch_array($newsQuery)现在返回NULL,直到您进行新查询.

尝试首先使用结果填充变量,然后循环该变量:

$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"];
}

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读