Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP while loop omits first entry from MySQL database select

Tags:

php

mysql

I have four rows in my table. Only three are shown.

$query  = "SELECT * FROM table";
$result = mysql_query($query);
$row    = mysql_fetch_array($result);

while($row = mysql_fetch_array($result)) {
    echo $row['id'];
}

The result is 234, but should be 1234.

What am I doing wrong?

like image 537
Kriem Avatar asked Sep 24 '26 04:09

Kriem


2 Answers

$row    = mysql_fetch_array($result);

This line already fetches the first entry. Thus in the while loop you fetch the second element.

Correctly it should be:

$query  = "SELECT * FROM table";
$result = mysql_query($query);

while ($row = mysql_fetch_array($result)) {
    echo $row['id'];
}

Alternatively:

$query  = "SELECT * FROM table";
$result = mysql_query($query);
$row    = mysql_fetch_array($result);

do {
    echo $row['id'];
} while ($row = mysql_fetch_array($result));
like image 77
NikiC Avatar answered Sep 27 '26 01:09

NikiC


You are already advancing the query buffer one row before the loop by calling mysql_fetch_array() outside of it. Remove that call and it should work as expected

like image 36
Eran Galperin Avatar answered Sep 27 '26 03:09

Eran Galperin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!