2

In the tutorial on accessing MySQL tables in PHP, they gave the code to list all values as:

$query = "SELECT * FROM example"; 

$result = mysql_query($query) or die(mysql_error());


while($row = mysql_fetch_array($result)){
    echo $row['name']. " - ". $row['age'];
    echo "<br />";
}

I understand how the while loop returns true when there is a row to print out and false when there are no more, but I don't understand why it doesn't work if I write:

$query = "SELECT * FROM example"; 

$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);

while($row){
    echo $row['name']. " - ". $row['age'];
    echo "<br />";
}

It just returns the first row, I assume this means it is always returning the value as true but I don't understand why.

Sebiddychef
  • 293
  • 5
  • 7
  • 11

5 Answers5

7

This:

$row = mysql_fetch_array($result)

while($row){
    echo $row['name']. " - ". $row['age'];
    echo "<br />";
}

doesn't work because $row will only take one value per execution which means that the while loop will run forever.

From the mysql_fetch_array doc:

Returns an array that corresponds to the fetched row and moves the internal data pointer ahead.

In the while($row = mysql_fetch_array($result)) version instead, the while's conditional expression will be executed at every loop, therefore moving the mysql internal results pointer forward (reading the next result).

Shoe
  • 74,840
  • 36
  • 166
  • 272
3

you should keep this

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

because, at every loop "turn", $row gets a new value. If you set the value for $row outside the while statement, $row will reman the same value.

BeNdErR
  • 17,471
  • 21
  • 72
  • 103
1

You need to use mysql_fetch_array function in the while loop like:

while(($row = mysql_fetch_array($result)) !== FALSE){
    echo $row['name']. " - ". $row['age'];
    echo "<br />";
}

The mysql_fetch_array function returns false if there is no record remaining. So loop it until it returns false.

asim-ishaq
  • 2,190
  • 5
  • 32
  • 55
1

Take a look at how PHP evaluates expressions to determine TRUE or FALSE. You will see that it evaluates NULL as false. When you execute:

 $row = mysql_fetch_array($result)

the $row variable either has a value because you got another row of data or it is NULL. If it has another row then the loop processes it. Otherwise the loop ends.

By removing the assignment you are taking the first value assigned which is the first row and then the loop runs forever because $row never evaluates to false.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
0

Because, in the second example, as soon as the first loop finishes, it doesn't execute mysql_fetch_array($result), whereas the first example it executes as it finishes each loop.

maethorr
  • 594
  • 4
  • 7