简体   繁体   中英

mysql_fetch_array while loop

I have a while loop that contains another while loop. Both loops are iterating over different mysql result sets. The problem is that the second time the outer while loop calls the inner while loop it doesn't run. Does Mysql_fetch_row discard itself after it has been iterated over?

Here is what the code looks like:

$counter = 0;
while ($r = mysql_fetch_row($result)){
    $col = "";
    $val = "";
    while($d = mysql_fetch_row($dictionary)){
        $key = $d[0];
        for($i= 0; $i< count($tableColumNames); $i++){
            if($tableColumNames[$i] == $key){
                $col .= "`".$d[1]."` ,";
                $val .= "`".$r[$i]."` ,";
                /* echo $tableColumNames[$i]." table ColumnName <br>";
                echo $d[1]." key<br>"; */               
            }           
        }
        echo $key."round".$counter."<br>";
    }
    var_dump ($col);
    var_dump ($val);
    $counter++;
    echo $counter;
}

And here is what the output is like: You can see that the $result holds four records and the output is showing that the loop is working correctly. However, the inner loop over the $dictionary result set doesn't run the second time $result is being iterated over. Any ideas why? I tried to use mysql_fetch_array as well but still the same result.

Thanks

在此处输入图片说明

When ever you are calling mysql_fetch_row($dictionary) It gives you a particular column details in the row and it deletes it from the $dictionary array.

So there are no elements for next use.

Instead of declaring $dictionary outside declare it in while loop. It will solve your problem.

$counter = 0;
while ($r = mysql_fetch_row($result)){
$col = "";
$val = "";
$dictionary=("Select * from database");//your own logic
while($d = mysql_fetch_row($dictionary)){
    $key = $d[0];
    for($i= 0; $i< count($tableColumNames); $i++){
        if($tableColumNames[$i] == $key){
            $col .= "`".$d[1]."` ,";
            $val .= "`".$r[$i]."` ,";
            /* echo $tableColumNames[$i]." table ColumnName <br>";
            echo $d[1]." key<br>"; */               
        }           
    }
    echo $key."round".$counter."<br>";
}
var_dump ($col);
var_dump ($val);
$counter++;
echo $counter;
}

or you can use mysql_data_seek() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM