2

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?

2 Answers 2

10
$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));
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.