Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: cannot loop through mysql rows more than once

Tags:

php

mysql

I'm working on pagination, and for some reason I cannot use mysql_fetch_array to loop through a result more than once.

//both $page and $imagesPerPage != 0
$offset = $page * $imagesPerPage
while ($row = mysql_fetch_array($result)) {
   $total_images++;
}
echo $total_images;
//echos correct amount
$row = null;


$images_to_offset = 0;
while ($row = mysql_fetch_array($result) && $images_to_offset < $offset) {
   $images_to_offset++;
}
echo $images_to_offset;
//echos 0... which is wrong

Should I be using a different php function to get row data in a database?

Thanks!

like image 747
user3871 Avatar asked Oct 02 '12 13:10

user3871


4 Answers

This is the error

while ($row = mysql_fetch_array($result)) {
   $total_images++;
}

once you fetched the array the array pointer set to the end.

use this

 $total_images=mysql_num_rows($result);

and

$images_to_offset=mysql_num_rows($result);

OR

To reset the position of pointer Use mysql_data_seek(). it moves internal result pointer

like image 191
StaticVariable Avatar answered Nov 19 '22 07:11

StaticVariable


If you wish to start fetching from the beginning after you've already fetched, you'll need you use mysql_data_seek().

Also, please note that the mysql line of functions have been deprecated, and the community is encouraging use instead of MySQLi or PDO_MySQL lines of functions.

like image 29
Jonathan M Avatar answered Nov 19 '22 07:11

Jonathan M


You could point the pointer back to the first row with mysql_data_seek.

mysql_data_seek($result, 0); 

Also see: http://ca2.php.net/manual/en/function.mysql-data-seek.php

like image 2
Sebass van Boxel Avatar answered Nov 19 '22 07:11

Sebass van Boxel


You have to 'rewind' the array, by using the mysql_data_seek function:

$offset = $page * $imagesPerPage
while ($row = mysql_fetch_array($result)) {
   $total_images++;
}
echo $total_images;
//echos correct amount
$row = null;

mysql_data_seek(); // <-- rewind to the beginning

$images_to_offset = 0;
while ($row = mysql_fetch_array($result) && $images_to_offset < $offset) {
   $images_to_offset++;
}
echo $images_to_offset;
like image 1
JvdBerg Avatar answered Nov 19 '22 06:11

JvdBerg