Forum Moderators: coopster

Message Too Old, No Replies

PHP while loop not returning all data available

         

Cherewest

3:43 am on Jan 14, 2007 (gmt 0)

10+ Year Member



The following code doesn't work as expected.

When I print the resulting array (useRow[]), the first row of results is not printed. I think maybe it's the 'while loop' as $totalRows does indicate the correct number of rows in the table and all the returned data in $row is correct. It's just missing a record.

(the table only has 5 rows and 4 columns)
$query= "SELECT * FROM myTable ORDER BY someField DESC";
//Connect to and query the database
$db=mysql_select_db($database_Con, $Con);
$results=mysql_query($query, $Con) or die(mysql_error());
$row=mysql_fetch_assoc($results);
$totalRows= mysql_num_rows($results);

//Get the results as an associative array and put each row into the numerically indexed array
$useRow=array();
while($row=mysql_fetch_assoc($results)){
$useRow[]=$row;
}
print_r($usedRow);

This seems pretty straight forward and should work. But I am stumped.
Any ideas?
Thanks.

eelixduppy

3:58 am on Jan 14, 2007 (gmt 0)



Welcome to WebmasterWorld!

Because you have this line:


$row=mysql_fetch_assoc($results);

The internal pointer is already advanced once, so the next time you call it within your while loop, it will start at the second row. You can achieve the same thing by elimination this line:


$query= "SELECT * FROM myTable ORDER BY someField DESC";
//Connect to and query the database
$db=mysql_select_db($database_Con, $Con);
$results=mysql_query($query, $Con) or die(mysql_error());
$totalRows= mysql_num_rows($results);
//Get the results as an associative array and put each row into the numerically indexed array
$useRow=array();
while($row=mysql_fetch_assoc($results)){
$useRow[]=$row;
}
echo '<pre>';
print_r($usedRow);
echo '</pre>';

Good luck! :)

Cherewest

3:59 am on Jan 14, 2007 (gmt 0)

10+ Year Member



I figured it out a minute after I posted the question.

I had already called $row before I used it in the while loop. So the pointer had already been advance to the second record in the table.

I'm working in auto mode. Perhaps I'll engage my brain now :-D.

Hope this helps someone.

Enjoy!

Cherewest

4:01 am on Jan 14, 2007 (gmt 0)

10+ Year Member



Thanks! eelixduppy. You're quick on teh keyboard!

eelixduppy

4:02 am on Jan 14, 2007 (gmt 0)



hehe...some would say I'm not fast enough! ;)

Glad you got everything sorted!