PHP-多个while($ row = mysql_fetch_array($ variable)){}错误 [英] PHP - Multiple while($row = mysql_fetch_array($variable)) { } ERRORS

查看:118
本文介绍了PHP-多个while($ row = mysql_fetch_array($ variable)){}错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我的语法可能无需代码即可描述.基本上,这应该很容易...但绝不容易.

Okay my syntax can probably be described without the code. Basically it should be easy...but never is.

我连续有2个循环...基本上是同一回事.我从数据库中选择*每个变量,然后我需要基于两个Sep构建一个2层javascript.变量.

I have 2 loops in a row...basically the same thing. I SELECT * every variable from my database, and then I need to build a 2 layer javascript based on two sep. variables.

所以

我有:

while ($row = mysql_fetch_array($myVariable)) {

// do events

}

然后在那

while ($row2 = mysql_fetch_array($myVariable)) {

// do events

}

由于某种原因,它在第二个上完全返回了NOTHING ...在某些地方我需要重设阵列,它可能结束了,然后我不能重新启动.这样一个基本的问题,但是我无法弄清楚我的一生中还有什么不对劲.那就是问题,这是一个一般的问题,它只是连续执行两次,并期望PHP每次都在保存我的SELECT语句的$ myVariable开头重新启动吗?

For some reason it's completely returning NOTHING on the second one...is there some where I need to reset my array, did it possibly end and then I can't just restart. Such a basic question, but I can't figure out what else could be wrong for the life of me. So thats the question, is that a general issue to just do that twice in a row and expect PHP to start over each time at the beginning of $myVariable which holds my SELECT statement?

谢谢...将全天检查并根据需要进行更新.我很想看到Stack Overflow的第一个计时器.

Thanks...will check all day and update as needed. First timer to Stack Overflow i'd love to see the help.

推荐答案

问题是查询返回 mysql_fetch_array 将推进该内部指针,并一次返回资源中的每一行.一旦在末尾(没有剩余的行),它将返回false.因此在最后一个循环中,$ row等于false,它退出while循环.指针不会重置.因此,在下一个while循环中,您调用mysql_fetch_array,该指针位于末尾,因此它返回false,从而完全绕过第二个while循环.您应该做的是一次遍历数据并将每一行存储到一个数组中.然后,您可以根据需要复制/循环数组,一切按预期进行.

The problem is that the query returns a resource. This resource has it's own internal pointer (counter to remember which row to return). mysql_fetch_array will advance that internal pointer and return each row from the resource one at a time. once it is at the end (no more rows left), it returns false. so on the last loop, $row equals false which exits the while loop. The pointer is not reset though. So on the next while loop, you call mysql_fetch_array, the pointer is at the end and so it returns false which completely bypasses the second while loop. What you should do, is loop through the data once and store each row into an array. Then you can copy/loop over the array as much as you want and everything works as expected.

$data = array();
while ($row = mysql_fetch_array($myVariable)) {
    $data[] = $row;
}
//now $data has all the rows. a simple foreach will loop over the data.
foreach($data as $row){
    //do events
    print_r($row);
}

//and you can loop over data again and again.
foreach($data as $row){
    //do events
    print_r($row);
}

这篇关于PHP-多个while($ row = mysql_fetch_array($ variable)){}错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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