PHP-MySql: Select previous row and next row from current ID
Tuesday, July 15th, 2008During the dark age, the simplest way to get previous row from current ID was using this query:
-
SELECT field1
-
FROM tablename
-
WHERE id = ($currentId - 1)
and to get next row:
-
SELECT field1
-
FROM tablename
-
WHERE id = ($currentId + 1)
But there’s a problem. Like common data, we need to delete some rows. For example, the current ID is 14 ($currentid = 14) , and i deleted row id number 13, when i run the query to get the previous row, the result will empty. The sql cannot find ID number 13 ($currentid - 1).
How to fix it?
Again, the first simplest way i got is to loop the ID. When it cannot find the first query, it calculate again by looping it with PHP.
-
<?
-
$ok = false;
-
$prev = $currentid - 1;
-
while($ok == false){
-
$sql = "select * from tablename where id = $prev ";
-
$data = $db->query($sql);
-
if(empty($data)){
-
$prev = $prev-1;
-
}else{
-
$ok = true;
-
}
-
}
-
?>
This is really bad idea. It will consume more resources by continually query the database. What happen when you deleted 10 rows from current ID?
There will be 10 looping with 10 query to database. How about deleted 100 rows?? You must be insane doing this.


