tags:

views:

123

answers:

3

In PHP/MySQL, what's the best way to generate a unique reference ID so that when a person submits his info to the database, he gets a reference number to follow up with his request?

I am already using the auto-increment feature from the database since the data needs to be unique every time a user submits information, but then I need to pick that specific data from the database in order to retrieve that incremented value and display it with PHP.

+1  A: 

rexem's comment is correct; then if you're using the basic mysql commands in PHP, you can use

$id = mysql_insert_id()

to retrieve the last insert'ed row's ID number (based on the primary key of that table).

richsage
+1  A: 

Hi,

I would probably go with the auto_increment field that you already have : it's a solution that works fine -- maybe concatenating it with something, to get, for instance "CMD123456", which is more "human-readable".

To get the last generated auto_increment for the currently active connection to the DB, you can use the mysql_insert_id function -- provided you are working with the family of mysql_* functions.

Just call it after you have done your insert query, and it'll get you the value of the auto_increment that has been generated by/for that one.


If using mysqli_*, you'll need mysqli_insert_id, and, if using PDO, you'll work with PDO::lastInsertId.

Pascal MARTIN
+1  A: 

If you want to use the auto_increment value you can execute select last_insert_id() after your insert.

last_insert_id() is a mysql function that returns the auto increment value from the last insert.

As others have noted some mysql libraries provide their own method for getting the last insert id

Craig
What if 12 people submit the form at the same time? Would there be a conflict?
Brad S
last_insert_id() is maintained per database connection. Since the connection is not shared between server instances each simultaneous submit has its own connection. Using PHP's persistent connections shouldn't change this.
Craig