开发者

PHP while loop omits first entry from MySQL database select

开发者 https://www.devze.com 2023-01-22 10:50 出处:网络
I have four rows in my table. Only three are shown. $query= \"SELECT * FROM table\"; $resu开发者_开发知识库lt = mysql_query($query);

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

$query  = "SELECT * FROM table";
$resu开发者_开发知识库lt = 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?


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消