fetch_assoc()在循环中仅工作一次 [英] fetch_assoc() works only once in a loop

查看:58
本文介绍了fetch_assoc()在循环中仅工作一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在遍历MySQL DB中的2个表(使用fetch_assoc()).我想在每次迭代中获取第一个表的当前ID和第二个表的所有ID,但是我仅在第一次迭代中获取第二个表的ID.从第二次迭代开始,仅返回第一张表的当前ID.我想知道我在做什么错.

I'm looping through 2 tables in MySQL DB (using fetch_assoc()). I would like to get the current id of the 1st table and all the ids of the second table on each iteration but I get the ids of the second table only on the first iteration. From the second iteration upwards, only the current id of the 1st table is returned. I would like to know what I'm doing wrong.

我已经尝试过Loops,并在这里查找了类似的问题,但是没有一个真正的帮助.

I've already tried for Loops and looked up similar questions here but none have really been of help.

<?php
$my_sqli = new mysqli('localhost', 'root', '', 'taskpro') or die(mysqli_error($my_sqli));
$data1 = $my_sqli->query("SELECT * FROM task_table") or die($my_sqli->error);
$data2 = $my_sqli->query("SELECT * FROM taskinfo") or die($my_sqli->error);

while ($row = $data1->fetch_assoc()) {
    echo "<br>";
    echo $row['id'];
    echo "<br>";

    while ($row2 = $data2->fetch_assoc()) {
        echo $row2['id'];
    } // end child loop

} // end parent loop

?>

这是我得到的结果

1

1234

2

3

4

5

6

7

8

9

10

推荐答案

最简单的方法是将query2中的所有值读入一个数组,然后在循环中输出该数组的内容:

The simplest thing to do is to read all the values from query2 into an array and then output the contents of the array in the loop:

$my_sqli = new mysqli('localhost', 'root', '', 'taskpro') or die(mysqli_error($my_sqli));
$data1 = $my_sqli->query("SELECT * FROM task_table") or die($my_sqli->error);
$data2 = $my_sqli->query("SELECT * FROM taskinfo") or die($my_sqli->error);

$rows2 = $data2->fetch_all(MYSQLI_ASSOC);
while ($row = $data1->fetch_assoc()) {
    echo "<br>";
    echo $row['id'];
    echo "<br>";

    foreach ($rows2 as $row2) {
        echo $row2['id'];
    } // end child loop

} // end parent loop

如果由于某些原因您确实需要遍历外部循环中的结果集,则可以使用

If for some reason you do need to iterate over the result set in the outer loop, you can use mysqli_data_seek to reset the pointer:

while ($row = $data1->fetch_assoc()) {
    echo "<br>";
    echo $row['id'];
    echo "<br>";

    while ($row2 = $data2->fetch_assoc()) {
        echo $row2['id'];
    } // end child loop
    // reset $data2 result pointer
    $data2->data_seek(0);

} // end parent loop

这篇关于fetch_assoc()在循环中仅工作一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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