Next available ID

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mwaheedf
Forum Newbie
Posts: 9
Joined: Wed Mar 21, 2012 12:32 pm

Next available ID

Post by mwaheedf »

I need to display the next available ID in the database. so say i have 5 rows in the database. the next available ID will be 6.

All i need is to do is store the ID number somewhere and every time an insert operation is carried out I can do $id=$id +1.

This is because I need the id to show on the form so I know what customer id this customer will have.

I have looked at count, max id and global variables but am becoming increasingly frustrated. something soo simple has taken up a lot of my time lol.
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Next available ID

Post by social_experiment »

Why not make a auto-incrementing column for this purpose?
mwaheedf wrote:I have looked at count, max id and global variables but am becoming increasingly frustrated.
COUNT() should work for this purpose; how did you implement it?
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
mwaheedf
Forum Newbie
Posts: 9
Joined: Wed Mar 21, 2012 12:32 pm

Re: Next available ID

Post by mwaheedf »

sorry, I am using auto-increment... however i want to display the next available one on my form..
in the script i have this
$query1 = 'SELECT MAX(customer_id) FROM customer;
$customer_id = mysql_query($query1);
echo $customer_id;//this should be the next available number...
in the body i have this...
<td customerID</td>
<td <?php echo $customerid; ?></td>

so basically i want to display the next available ID.....
EXAMPLE
CUSTOMER ID, NAME, AGE
1,GUV,45
2,PAUL,55

when I go to the add form it should show 3
and then i can enter the name and age....

then the script will use the insert to enter the id IN two different tables as well as the data.

the above is just an example to try and demonstrate the problem i am having.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Next available ID

Post by requinix »

As long as you never assume that ID is the one that will be used, and that it's only probably the ID, then you can do a query with MAX(id)+1.

A more correct way would be to do a SHOW TABLE STATUS and read the Auto_increment value.
Post Reply