无限PHP while循环 [英] Infinite PHP while loop

查看:293
本文介绍了无限PHP while循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用基本的PHP while循环时遇到了一些麻烦,每次在浏览器中启动test_post.php文件时,我都会遇到一个永无止境的循环,而且我不知道自己缺少什么!

I am having some trouble with a basic PHP while loop, everytime I launch my test_post.php file in my browser, I get a never ending loop, and I have no idea what I am missing!

这是我的PHP代码:

<?php

 mysql_connect('localhost', 'admin', '1234') or die(mysql_error());
 mysql_select_db('json');
 $test = mysql_query('SELECT user,pass FROM login WHERE user="john"');

 $row = mysql_fetch_array($test, true);

 while($row) {
  echo "Username: ".$row['user']." Password: ".$row['pass']."<br />";
 };
?>

我的mySQL数据库中有三个符合条件的条目,但它会无限循环遍历第一个条目!

I have three entries in my mySQL database that meet that criteria, but it keeps looping through the first one infinitely!

我试图从数据库中获取一个数组,然后将其转换为一个JSON对象,该对象可以传递回以填充下拉列表.

I am trying to get an array from the database and then convert it into a JSON object that can be passed back to populate a drop down list.

我还尝试使用PHP的count函数来获取数组中的条目数量,以限制while循环执行的次数,但这甚至导致永无休止的循环.

I also tried using PHP's count function to get the amount of entries in the array to limit the amount of times the while loop will execute, but even that results in a never ending loop.

我的数据库结构由一个名为login的表组成,该表包含3列,即id,user和pass,其中有3个条目,其'user'值为'john'.

My database structure consists of one table named login, which contains 3 columns, namely id, user and pass, within which I have 3 entries that have a 'user' value of 'john'.

关于可能出什么问题的任何想法吗?

Any ideas on what could be wrong?

PS:由于某种原因,我无法将代码格式应用于我的帖子,工具栏消失了!

PS: I couldn't apply code formatting to my post for some reason, the toolbar is gone!

推荐答案

正如@froadie所提到的,您永远不会更改$row,因此它将始终计算为true(并因此是无限循环).

As @froadie mentions, you never change $row, so it will always evaluate to true (and hence the infinite loop).

你想要的是:

while ($row = mysql_fetch_array($test, true)) {

或者,或者您可以内联更新它:

Either that, or you could update it inline:

$row = mysql_fetch_array($test, true));

while ($row) {
    //... do your echo here

    $row = mysql_fetch_array($test, true));
}

但是要点是,您需要在while循环中对它执行某事,否则您将始终有一个无限循环...

But the point is that you need to do something to it inside the while loop, otherwise you'll always have an infinite loop...

这篇关于无限PHP while循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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