- Forums
- MYSQL
- How to Get Next and Previous Record in MySQL Database
for the longest time i struggle to find an answer for this - i wanted to know how to query a databse table where the numbers were not consecutive but to only display the records i needed [2329], Last Updated: Mon Jun 24, 2024
Webune Support
Fri Sep 10, 2010
6 Comments
1105 Visits
for the longest time i struggle to find an answer for this.
whenever i would do my query in my sql with php, i could only get the next record by adding a 1
for example, lets say i have this
$CurrentId = 54;
$NextId = $CurrentId + 1;
$query = "SELECT * FROM mytable WHERE id = $NextId";
OUTPUT: 55as you can see, from my query above, i would get the record 55. but how about if i had a field in my database called hidden it looked like this:
id 54
visible = yes
id 55
visible = no
id 56
visible = yes
so if i had a table with the above information, and my current id was 54, using the PHP code above would result in my $NextId as 55, but i dont want 55, i want 56, because id 55 is not visible..
so this is how you would do the query correctly:
$CurrentId = 54;
$query = "SELECT * FROM mytable WHERE id > $CurrentId AND visible = 'yes' LIMIT 1";
OUTPUT: 56as yo can see, the query ignored id 55 - why? because id 55 visible value is equals to no, and the query specifies, only to get records where visible equals to 'yes'
hope that helps
scottklarr
https://www.webune.com/forums/20100910cgcp.html