rss
twitter
  •  

PHP-MySql: Select previous row and next row from current ID

| Posted in Programming |

30

During the dark age, the simplest way to get previous row from current ID was using this query:

  1. SELECT field1
  2. FROM tablename
  3. WHERE id = ($currentId - 1)

and to get next row:

  1. SELECT field1
  2. FROM tablename
  3. 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.

//the bad way..
  1. <?
  2. $ok = false;
  3. $prev = $currentid - 1;
  4. while($ok == false){
  5.    $sql = "select * from tablename where id = $prev ";
  6.    $data = $db->query($sql);
  7.    if(empty($data)){
  8.       $prev = $prev-1;
  9.    }else{
  10.       $ok = true;
  11.    }
  12. }
  13. ?>

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:

  1. SELECT field1
  2. FROM tablename
  3. WHERE id < $currentid
  4. ORDER BY id DESC
  5. LIMIT 1

And the next row:

  1. SELECT field1
  2. FROM tablename
  3. WHERE ID > $currentid
  4. ORDER BY id ASC
  5. 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.

VN:F [1.9.3_1094]
Rating: 9.3/10 (6 votes cast)
VN:F [1.9.3_1094]
Rating: +3 (from 3 votes)
PHP-MySql: Select previous row and next row from current ID, 9.3 out of 10 based on 6 ratings

Comments (30)

sayangnya trik ini tidak bisa diterapkan jika ID bukan bertipe data numerik (integer, float, dll)

solusinya mungkin seperti ini :

kita harus tahu di posisi row keberapakah data yang saat ini ditampilkan, simpan ke variabel misal $currentRow

kode :

$goNext = $currentRow + 1;
$goPrev = $currentRow – 1;

kemudian link untuk navigasinya jadi seperti ini :
Prev
Next

gunakan passing variabel $currentRow dari navigasi untuk query berikut :

SELECT * FROM something LIMIT $currentRow, 1

selengkapnya >>

VA:F [1.9.3_1094]
Rating: 2.7/5 (3 votes cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Thank you so much for this. I’ve been looking for a more efficient way of doing this for some time. Its a simple, elegant solution.

VA:F [1.9.3_1094]
Rating: 3.7/5 (3 votes cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Thank’s a lot. Indeed it is a elegant solution. Only one problem: if I have reached the last row (or the first row) and then I put the next-button (previous button) I get a empty form mask. How can I avoid this?

Two ideas (logically, no technical):
1. If I reached the last row (last dataset) the next button is disabled.
What is the technical way to program this?

2. If I reached the last row pushing the next-button fetches again the last row.
How can I program this?

Thanks a lot for all helpful suggestions

Martin

VA:F [1.9.3_1094]
Rating: 4.0/5 (4 votes cast)
VA:F [1.9.3_1094]
Rating: 0 (from 2 votes)

1. Add this:
$data = (your sql query);
if(empty($data))
echo “<input type=’button’ value=’next’ disabled=’true’ />”;

2. Add more query. or add ‘if-else’ case on your query.

VN:F [1.9.3_1094]
Rating: 3.8/5 (5 votes cast)
VN:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Nice and simple idea ;)

VA:F [1.9.3_1094]
Rating: 2.0/5 (2 votes cast)
VA:F [1.9.3_1094]
Rating: -2 (from 2 votes)

Very nice blog. I appreciate your efforts.

Can you please let me is it possible with one query?

Kunal Mehta

http://elevatesoftsolutions.in/post/2009/01/11/how-portal-iframes-open-splendid-crm-page-like-sugar-crm-php.aspx

VA:F [1.9.3_1094]
Rating: 5.0/5 (2 votes cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Thanks a lot for this useful information. I have tried this and it worked perfectly. I highly appreciate this solution. Previously, i used to write like id=current_id + 1. I want next id to move the current record down. But as the next id might have got deleted, i have to click on down button many times to move the current record down, till i reach the next existing id in the table. So i used like “seelct id > current_id” and it instantly moves the current record down and vice-versa, moves up. Thanks a lot.

VA:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

it’s 100% not working if you have random id.. or delete 1 id both another.

VA:F [1.9.3_1094]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Up’s sorry i didn’t lookout your solution:D
it’s working**
thx

VA:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

How if not sorting by id.. but by date?? like wordpress??

VA:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Do the same but change the date to timestamp strtotime then compare sizes.

VA:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

@einchi: the same, select the next/previous date and proceed.

thanks a lot for this solution, it’s brilliant.

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Gut!

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

You rock dude !.. Really cool tip

VA:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Hello webmaster
I would like to share with you a link to your site
write me here preo@mail.ru

VA:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Perfect!Amazing!Super!Thank you very much

==
http://www.vinyladdiction.tv/sitemap.xml

VA:F [1.9.3_1094]
Rating: 4.0/5 (2 votes cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Кайтсерфинг, школа кайтсерфинга, обучение кайтсерфингу,кайтинг, кайтинг обучение, кайт школа, кайт школа вьетнам.

VA:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Couldn’t I get the previous and next items in one query by changing the limit to 3 and using the first and third row of the resultset?

VA:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

forget about it, of course not.

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

But you could UNION ALL the two queries if you wished to retrieve both values in one query.

VA:F [1.9.3_1094]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: +1 (from 1 vote)

UNION example (including a subquery to get sorting for certain ID.

(SELECT sorting
FROM table
WHERE sorting (SELECT sorting FROM table WHERE itemid = ?)
AND groupid = ?
ORDER BY sorting ASC
LIMIT 1)

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

wellwell the editor cut half of my query… I’m giving up

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

How to fix if previous / next data is empty?

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -2 (from 2 votes)

will result empty or null data.
see my previous comment.

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

thank you so much friend!
your SQL code, very usefull for me :)

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Thanks a lot for writing this. I was looking for a good solution to getting prev/next rows and this is perfect!

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -2 (from 2 votes)

your welcome..
hope this is usefull..

VN:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VN:F [1.9.3_1094]
Rating: -1 (from 1 vote)

Hi

Very smart!

Like the others though, I’m trying to verify if the next and previous results in the DB the easy way. I figured I could cheat doing this:

$Query = “select * from `welcome_images` where `id`’$_HTTP[image]‘ order by `id` asc limit 3″

($_HTTP = $_GET + $_POST)

Unfortunately.. it doesn’t work!

I could use 3 queries and test all 3 of them but .. thats the long hard undynamic way!

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 3 votes)

just to say for some reason my SQL didn’t come out right in the reply above..

VA:F [1.9.3_1094]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.3_1094]
Rating: -1 (from 1 vote)

How to sort by string instead of ID?

VA:F [1.9.3_1094]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Post a comment