PDA

View Full Version : PHP pagination : records with non-consecutive id numbers (?)



kompuser
September 7th, 2007, 05:34 AM
hi all
I have to set a pagination php code based on this useful script.




if (isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id = 1;
}

$query = "SELECT count(*) FROM mytable";
$result = mysql_query($query, $db) or trigger_error("SQL", E_USER_ERROR);
$query_data = mysql_fetch_row($result);
$numrows = $query_data[0];
$rows_per_page = 1;
$lastpage = ceil($numrows/$rows_per_page);
$id = (int)$id;

if ($id < 1) {
$id = 1;
} elseif ($id > $lastpage) {
$id = $lastpage;
}

Then the following are set to create the previous/next links



if ($id == 1) {
echo " FIRST ";
} else {
echo " <a href='$PHP_SELF'?id=1'>FIRST</a> ";
$prevpage = $id-1;
echo " <a href='$PHP_SELF?id=$prevpage'>PREV</a> ";
}
if ($id == $lastpage) {
echo " LAST ";
} else {
$nextpage = $id+1;
echo " <a href='$PHP_SELF?id=$nextpage'>NEXT</a> ";
echo " <a href='$PHP_SELF?id=$lastpage'>LAST</a> ";
}

Then I have some code to retrive the actual data. (not shown here)

The main problem is that , On 'mytable' which hold all the records, the ID column - which is SET as Auto-increment, doesn't show consecutive ID numbers (such as 1,2,3,4...) because of some DELETE done by the backoffice.

So My question is : How to retrieve the 'next available row id' stating that it will not ever be the next following number (that's why $id+1 is causing problem I guess) ?


thanks
K.

soulwire
September 7th, 2007, 05:53 AM
Im not a PHP expert, but if you create an array of IDs from your first MYSQL '$query' (which returns all rows) then you can use something akin to $nextpage = $arrayPos + 1 which would just return the next array element regardless of its id.

kompuser
September 7th, 2007, 06:03 AM
now that was fast :-)
thanks, i have to try this trick.

soulwire
September 7th, 2007, 06:06 AM
Lol, no worries! Good luck :)