rss
twitter
  •  

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

| Posted in Programming |

55

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.13_1145]
Rating: 8.6/10 (38 votes cast)
VN:F [1.9.13_1145]
Rating: +7 (from 11 votes)
PHP-MySql: Select previous row and next row from current ID, 8.6 out of 10 based on 38 ratings

Comments (55)

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.13_1145]
Rating: 2.8/5 (5 votes cast)
VA:F [1.9.13_1145]
Rating: -4 (from 6 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.

VA:F [1.9.13_1145]
Rating: 3.4/5 (5 votes cast)
VA:F [1.9.13_1145]
Rating: -2 (from 4 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

VA:F [1.9.13_1145]
Rating: 3.9/5 (7 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 6 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.13_1145]
Rating: 4.3/5 (8 votes cast)
VN:F [1.9.13_1145]
Rating: -1 (from 1 vote)

Nice and simple idea ;)

VA:F [1.9.13_1145]
Rating: 3.0/5 (5 votes cast)
VA:F [1.9.13_1145]
Rating: -4 (from 4 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.13_1145]
Rating: 3.4/5 (5 votes cast)
VA:F [1.9.13_1145]
Rating: -3 (from 3 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.

VA:F [1.9.13_1145]
Rating: 4.2/5 (5 votes cast)
VA:F [1.9.13_1145]
Rating: -2 (from 2 votes)

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

VA:F [1.9.13_1145]
Rating: 3.4/5 (5 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 2 votes)

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

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

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

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: -2 (from 2 votes)

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

VA:F [1.9.13_1145]
Rating: 4.2/5 (5 votes cast)
VA:F [1.9.13_1145]
Rating: -1 (from 3 votes)

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

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

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

Gut!

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

You rock dude !.. Really cool tip

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: -2 (from 2 votes)

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

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: -2 (from 2 votes)

Perfect!Amazing!Super!Thank you very much

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

VA:F [1.9.13_1145]
Rating: 3.5/5 (4 votes cast)
VA:F [1.9.13_1145]
Rating: -2 (from 2 votes)

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

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: -2 (from 2 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?

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: -2 (from 2 votes)

forget about it, of course not.

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
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.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
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.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: -1 (from 1 vote)

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

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

How to fix if previous / next data is empty?

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

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

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

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

VA:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
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.13_1145]
Rating: 3.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: -2 (from 2 votes)

your welcome..
hope this is usefull..

VN:F [1.9.13_1145]
Rating: 3.0/5 (2 votes cast)
VN:F [1.9.13_1145]
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.13_1145]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.13_1145]
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.13_1145]
Rating: 1.0/5 (1 vote cast)
VA:F [1.9.13_1145]
Rating: -2 (from 2 votes)

How to sort by string instead of ID?

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

id +1 is realy easy way if you have autoincrement and no deleted post, your solution is great

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: -1 (from 1 vote)

Yes I was also wondering how you would go about this, if you were to search the next entry on name so a string value?
Thanks for the help :)

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Saudara Vandai..

newbie nih…,

saya ketemu ini blog, juga karena lagi bingung
untuk link prev – next panggil baris data.

seperti yg bak wan bilang,
soalnya, “manggil” gak liwat numerik id,
tapi liwat string text dari file jpg.
(itu juga hasil utak-atik kopas kode yg udh ada).

pingin nerapin ide bakwan…masih bingung…
he-he-he…:)

bangga juga, anak2 indo banyak yg pinter2.

makasi atas postingnya.

salam.

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

you’re god dude …………… :)

Thank you so much

VA:F [1.9.13_1145]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.13_1145]
Rating: +3 (from 3 votes)

thank you!!

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Thank you!

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

how itsworks if it is a random id
in some case id can be a higher value and some tomes it will come lower than the previous

VA:F [1.9.13_1145]
Rating: 5.0/5 (2 votes cast)
VA:F [1.9.13_1145]
Rating: +1 (from 1 vote)

no problem, just change the ORDER BY with any field..

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.13_1145]
Rating: +1 (from 1 vote)

Unfortunately that’s not true. If you order by time, for instance, the id may be less than the given id while the time could be greater. I believe a subquery would be necessary.

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

i want to get some records which has been added after a particular id
there is no auto increment id for the table

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Nice tutorial. Simply elegant and effective.

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

hi this is pretty neat. unlike on what i did to my project where i query all id and put these on an array variable then access it one by one. this will save me more time and resources. thanks ill try this right away.

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

I realy like your solution! this helps me alot.
btw, i like your way of explaining the scripts. keep it up!

VA:F [1.9.13_1145]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Thanks! used it at my website. Easy to use!

VA:F [1.9.13_1145]
Rating: 5.0/5 (1 vote cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Following is a complete code for displaying Current Record With Previous, Next Record button

0) {

$info = mysql_fetch_assoc($result);
} else {
die(‘Not found’);
}

// Prev id
$sql2 = “SELECT * FROM user_login WHERE id 0) {
$prevrow = mysql_fetch_assoc($result2);
// echo ”. print_r($prevrow,true) . ”;
$previd=$prevrow['id'];
// echo “Prev = “.$previd.”";
}

// Next id
$sql1 = “SELECT * FROM user_login WHERE id > {$curid} LIMIT 1″;

$result1 = mysql_query($sql1);
if (mysql_num_rows($result1)>0) {
$nextrow = mysql_fetch_assoc($result1);
// echo ”. print_r($nextrow,true) . ”;
$nextid=$nextrow['id'];
// echo “Next = “.$nextid.”";
}

} else {
// No form has been submitted so use the lowest id and grab its info
$sql = “SELECT id,username,password FROM user_login WHERE id > 0″;

$result = mysql_query($sql);
if (mysql_num_rows($result)>0) {

$info = mysql_fetch_assoc($result);

$sql1 = “SELECT * FROM user_login WHERE id > {$info['id']} LIMIT 1″;

$result1 = mysql_query($sql1);
if (mysql_num_rows($result1)>0) {
$nextrow = mysql_fetch_assoc($result1);
$nextid=$nextrow['id'];
}
}
}
if (isset($info)) {
$content = ”.print_r($info,true).”;

} else {
$content = ‘Nothing in the db :( ‘;
}
?>

Next prev

Info

<input type="submit" name="id[]” value=”prev”/>

<input type="submit" name="id[]” value=”next”/>

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

// Prev id
$sql2 = “SELECT * FROM user_login WHERE id 0) {
$prevrow = mysql_fetch_assoc($result2);
// echo ”. print_r($prevrow,true) . ”;
$previd=$prevrow['id'];
// echo “Prev = “.$previd.”";
}

// Next id
$sql1 = “SELECT * FROM user_login WHERE id > {$curid} LIMIT 1″;

$result1 = mysql_query($sql1);
if (mysql_num_rows($result1)>0) {
$nextrow = mysql_fetch_assoc($result1);
// echo ”. print_r($nextrow,true) . ”;
$nextid=$nextrow['id'];
// echo “Next = “.$nextid.”";
}

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

BRRILLIANT!!! you sir saved me hours.

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

thnx

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Here’s what I came up with for ordering by a separate field (time):

SELECT id
FROM posts
WHERE time >= (SELECT MAX(time)
FROM posts
WHERE time
(SELECT time
FROM posts
WHERE id = $id))

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Some thing happened to the less-than symbol:

the second WHERE should be:

WHERE time <

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

That chopped off the rest of the query. Here’s the rest:

ORDER BY time ASC
LIMIT 3

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

With one query that returns three values (or two if its the last row): last, current and next. It only fails if the value of id is the first row. If you get an empty return value, just execute the following to get the id of the second row:

(see next post)

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

SELECT id
FROM posts
WHERE time = (SELECT MIN(time)
FROM posts
WHERE time >
(SELECT time
FROM posts
WHERE id = $id))

VA:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VA:F [1.9.13_1145]
Rating: 0 (from 0 votes)

After a couple of hours with a BACK NEXT problem to show results on a particular query you gave me the cleanest solution ever.
Tons of thanks

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

Post a comment