tags:

views:

73

answers:

4

Hi guys, 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!

Here is my PHP code:

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

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

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.

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.

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: I couldn't apply code formatting to my post for some reason, the toolbar is gone!

+8  A: 

Nothing changes $row within the loop, so while($row) continuously evaluates to true

froadie
+4  A: 

$row is the same value. Try reassigning it in the while().

meder
+6  A: 

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

That will actually update for you then.

cbattlegear
+8  A: 

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

What I think you want is:

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

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

ircmaxell
Thanx, that worked! I can see where I went wrong now, I figured that if I counted the amount of entries in the array and evaluated it in the while loop that it might work, but that didn't either, but thanx again to everyone for the fast replies, if I could give everyone a tick I would! ;)