SQL PHP HTML ASP JavaScript articles and free scripts to download
 
 

mysql_insert_id() to get the number created after insert command from auto increment field

On many occasions we want to generate a unique ID from the operation we do on a database. For example take the case of generating a trouble ticket number in case of a help desk. Here a ticket number is generated while the record is inserted to the table. This ticket number is nothing but the value of an auto incremented numeric field, which is unique also. Now in this case once the record is created we have to display or process (sending mail etc) the trouble ticket number (auto incremented unique ID) to the system. Here we will use mysql_insert_id() function to get the id generated after the insert command. We have to just echo or print the mysql_insert_id() to show the trouble ticket number. Here is an example of this. We will start with an insert command.

$query=mysql_query(“insert into help_desk(userid,type,domain,detail) values('$userid','$type','$domain','$detail')”);

/* Note that here auto increment field is not shown as it automatically add the next incremented value with every insert command */

echo "Your trouble ticket number is = " mysql_insert_id();
Related Tutorial
Generate auto increment number

Number of rows affected by a query


This way we can display the generated ID of auto increment field of recent insert command.

Discuss this tutorial at forum

List of SQL Tutorials


Further readings
MySQL Auto Increment field to generate unique record ID
How to start auto increment value from a predefined value ?
mysql_insert_id() to get the auto increment number of just inserted record
Scripts
PHP
JavaScript
SQL Tutorial List
SQL (Home)
mysql_affected_rows mysql_change_user mysql_close mysql_connect mysql_create_db mysql_data_seek mysql_db_name mysql_db_query mysql_drop_db mysql_errno mysql_error mysql_fetch_array mysql_fetch_assoc mysql_fetch_field mysql_fetch_lengths mysql_fetch_row mysql_field_flags mysql_field_len mysql_field_name mysql_field_seek mysql_field_table mysql_field_type mysql_free_result mysql_insert_id mysql_list_dbs mysql_list_fields mysql_list_tables mysql_num_fields mysql_num_rows mysql_pconnect mysql_query mysql_result mysql_select_db mysql_tablename
SQL site Map
Knowledge Management
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.