-1

I need to display the next id from a table but if there isn't a next id, I'll display the first id of the table.

Despite a lot of tries, I was just able to display next id if next id follow +1 like my sample Can you help me to custom my script ? Thank you very much for helping

<?php // verify that id+1 exist 
$verif_page_next = $planning_id +1;

$req = mysql_query("SELECT id FROM planning WHERE id = '" . $verif_page_next . "'") 
or exit(mysql_error());
if (mysql_num_rows($req) == 1) {
     $next_page =  $verif_page_next ;
}

// we start the first id 
else {
     $next_page =  1 ;
}


?>

So, if I delete an ID (e.g the ID 3), it restart to the first ID, and I wish to jump to the ID n° 4

Paul R
  • 105
  • 4
  • 2
    What exactly are you trying to achieve with this? Why don't you use auto increment as id? – Shadow Nov 11 '15 at 21:38
  • wat is table structure, is the field "id" is a autoincremented ? – HashSu Nov 11 '15 at 21:39
  • sounds like you're trying to do pagination and something "broke" somewhere. Did you or somebody go and delete something and you're trying to compensate for it? – Funk Forty Niner Nov 11 '15 at 21:45
  • [Your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Nov 11 '15 at 21:48
  • If you can, you should [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really not hard](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Nov 11 '15 at 21:48

1 Answers1

1

You can select all ids bigger than the active one and only return the smallest of them. This way you get the next one.

SELECT id FROM planning WHERE id > :id ORDER BY id LIMIT 1

with binding :id to $planning_id

clemens321
  • 2,103
  • 12
  • 18