During 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.
So what’s the solution?
We’ll not using the equal ( = ) operator since we must find the exact ID first. We will use the smaller and larger operator ( < > ) and combine it with “limit”.
Query to get the previous row:
-
SELECT field1
-
FROM tablename
-
WHERE id < $currentid
-
ORDER BY id DESC
-
LIMIT 1
And the next row:
-
SELECT field1
-
FROM tablename
-
WHERE ID > $currentid
-
ORDER BY id ASC
-
LIMIT 1
Simply, find the smaller ID from the current ID, sort it by descending, and limit by 1 to ensure we got the exactly previous row. And the same way for the next row. Get the larger ID from the current ID, sort it by ascending, and limit by 1.
No more resource wasting.
for anchor tag, what code code i used to disable the already exist anchor in php when all record empty in database
Hi,
I’m kind of new with the SQL queries and your post really helped me. It was exactly what I was looking for.
Thanks,
Omar
I’ve been looking for a clean and simple solution to do this and you’ve shown that simplicity can get it done!
Nice work, Cheers!
And what if we reach end of records and want to start over from first, and viceversa if moving to previous? (i.e looping over)
I want to ask one, how do I retrieve the current value of ID in PHP, Tks
Very simple, I can’t believe I was stumped for so long on this. Very logical explanation.
Thanks!
Hi,
how can i perform this operation on 3 columns in php ?
Sr A B C
1 200 100 1000
2 300 0 700
C2 = C1 – (A2 + B2)
——-
Thanks
what if the last number of row? like 1-34 ? 35 cannot find the id…
I LOVE U… You idea very amazing…
good, finally one clean solution 😀