tcd
tcd

Reputation: 1605

MySQL Query isn't printing all table data

Probably a simple solution here, but here is my code:

<?php
include("connect.php");
$data = mysql_query("SELECT * FROM table ORDER BY name");
$info = mysql_fetch_array($data);
?>

and then printing it with:

<select>
 <?php
  while($info = mysql_fetch_array($data)) {
     echo '<option value="'.$info['value'].'" rel="'.$info['del'].'">'.$info['name'].'</option>';
  }
 ?>
</select>

For some reason it's returning all results except for the very first one? Ex. I'm ordering by name and the first one should be Apples (id = 9), but it's skipping that and returning Blueberries (id = 5)

Thanks for any help!

Upvotes: 1

Views: 148

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270617

You are calling mysql_fetch_array() immediately after mysql_query() before your loop, which retrieves one row into $info and advances the record pointer to the second row. When you then enter your fetch loop, the rowset is already pointing to the second row.

$data = mysql_query("SELECT * FROM table ORDER BY name");
// Don't do this!
// $info = mysql_fetch_array($data);
// Instead just proceed with your while loop to fetch rows...

Upvotes: 2

andrewsi
andrewsi

Reputation: 10732

$data = mysql_query("SELECT * FROM table ORDER BY name");
$info = mysql_fetch_array($data);

That first mysql_fetch_array line loads a row of data; when you go into the for loop, that then loads the next row, so the first row is discarded.

The easiest solution is just to remove that first call.

Upvotes: 2

Related Questions