Next button that skips entry if id does not exist

I created a next (and previous) button that increments the id by one when the button is clicked, my issue is that some id’s don’t exist anymore. How can I say “if id does not exist, go to next”.

Here’s the code that successfully increments by one when the button is hit
[php]if(isset($_POST[‘next’])){

$judgment_id= $judgment_id +1;

//Then say that if judgment_id was incremented from 106 to 107 and 107 no longer exists, how can that id be skipped?
}[/php]

very basic but it does the job…almost.

use a database query to pull the previous and next id from the table

Like:

$id is the current id.

[php]
$nq = mysql_query(“SELECT id FROM table WHERE id > ‘$id’ ORDER BY id LIMIT 1”);
$nr = mysql_fetch_object($nq);

$pq = mysql_query(“SELECT id FROM table WHERE id < ‘$id’ ORDER BY id DESC LIMIT 1”);
$pr = mysql_fetch_object($pq);
?>

<?php if($pr->id != ''){?>Previous<?php } ?> <?php if($nr->id != ''){?>Next<?php } ?>

[/php]

First off, yes, awesome.

Second I’m having issues with the query. I can echo back $id and it returns the correct id. When I echo $nr or $pr it returns nothing.

where did I mess up?

I replaced “id” with judgment_id
[php]$nq = mysql_query(“SELECT judgment_id FROM judgment WHERE judgment_id > ‘$id’ ORDER BY judgment_id ASC LIMIT 1”);
$nr = mysql_fetch_object($nq);

$pq = mysql_query(“SELECT judgment_id FROM judgment WHERE judgment_id < ‘$id’ ORDER BY judgment_id DESC LIMIT 1”);
$pr = mysql_fetch_object($pq);[/php]

$nr is on object so you can’t echo it instead use the item inside the object you need like $nr->judgment_id

to see the contents of the object you can use print_r:

[php]echo “

”;
echo print_r($nr);
echo “
”;[/php]

Excellent, works great. Thank you very much.

I also added an else{echo " No more posts this way"} statement if there are no more posts in that direction.

Here’s final code…
[php]<?php
// Next and Previous Buttons
$nq = mysql_query(“SELECT judgment_id FROM judgment WHERE judgment_id > ‘$id’ ORDER BY judgment_id ASC LIMIT 1”);
$nr = mysql_fetch_object($nq);

$pq = mysql_query("SELECT judgment_id FROM judgment WHERE judgment_id < '$id' ORDER BY judgment_id DESC LIMIT 1");
$pr = mysql_fetch_object($pq);

?>

<?php if($pr->judgment_id != ''){?>Previous<?php } else { echo "
No more posts this way :(
";}?> <?php if($nr->judgment_id != ''){?>Next<?php } else { echo "
No more posts this way :(
";} ?>[/php]
Sponsor our Newsletter | Privacy Policy | Terms of Service