rss
twitter
  •  

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

| Posted in Programming |

23

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.7.2_963]
Rating: 8.7/10 (3 votes cast)
VN:F [1.7.2_963]
Rating: +2 (from 2 votes)

Comments (23)

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 >>

UN:F [1.7.2_963]
Rating: 1.0/5 (1 vote cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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.

UN:F [1.7.2_963]
Rating: 2.0/5 (1 vote cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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

UN:F [1.7.2_963]
Rating: 3.0/5 (2 votes cast)
UN:F [1.7.2_963]
Rating: +1 (from 1 vote)

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.

UA:F [1.7.2_963]
Rating: 5.0/5 (2 votes cast)
UA:F [1.7.2_963]
Rating: 0 (from 0 votes)

Nice and simple idea ;)

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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.

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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

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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

Gut!

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

You rock dude !.. Really cool tip

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

Perfect!Amazing!Super!Thank you very much

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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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?

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

forget about it, of course not.

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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)

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

How to fix if previous / next data is empty?

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: -1 (from 1 vote)

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

UN:F [1.7.2_963]
Rating: 0.0/5 (0 votes cast)
UN:F [1.7.2_963]
Rating: 0 (from 0 votes)

Post a comment