Jump to content

[SOLVED] NEXT AVAILABLE NUMBER IN SEQENCE


dlebowski
 Share

Recommended Posts

I have a php/mysql page site that I am putting together and what I need is a mysql query that will query the database, select a specific table, a specific column, and output the next available number in sequence that has not been assigned yet.  For example, this database is a customer database with each customer having their own ID.  Every time I add a new customer, I have to know what ID is available.  I would like the DB query to tell me what the next available number is.  Any help on this would be great.  Thanks in advance.

 

-Ryan

Link to comment
Share on other sites

If the table containing the customers has a customer ID number which is set to auto increment and primary key then the next available ID number would be the last one plus 1.

 

Every time you insert a row (customer) you can get this by using this:

<?php
  //mysql query to insert a new customer
  $nextID=mysql_insert_id()+1;
?>

 

If you want to get this at any other time something like this would work:

<?php
  $fetch=mysql_fetch_assoc(mysql_query("SELECT `id` FROM `customers` ORDER BY `id` DESC LIMIT 1"));
  $nextID=$fetch['id']+1;
?>

Link to comment
Share on other sites

Got it to work by doing this:

 

<?php
mysql_connect('localhost');
mysql_select_db('test');

$res = mysql_query('select customer_id FROM customer ORDER BY customer_id' );
$j = mysql_num_rows($res);
$i = 0;
while ($i++ < $j and mysql_result($res, $i - 1, 0) == $i);
echo 'Next available number is: ', $i;
?>

Link to comment
Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.