Blog Search
Latest Posts
New Educational Media Website Launch
Trevor Laurency Fitness Website Launch
Recent Recommended Links - April 2008
Web Apps on Your Desktop with Mozilla Prism
Recent Recommended Links - March 2008
Ubuntu Linux - Persistent sudo root
Controlling PHP Register Globals Using .htaccess File
Javascript Essentials - Date Pickers (Calendars)
New Acuras Website Coming Soon
Blog Archive
Browse by Subject
AJAX
Apache
CMS
CSS
HTML
Java
JavaScript
Links
Linux
Mac
MySQL
Pascal
PHP
postgreSQL
RSS
Ruby
SEO
Web Dev News
Windows
XML
Other Resources
Computer Science Student Articles
PHP: Use mysql_insert_id() To Get The Last Entered Auto Increment Value
Published: 6th Apr 2006
Revised: 6th Apr 2006
The mysql_insert_id() function is a very handy PHP function that enables you to get the auto incremented value that was created from the last MySQL query executed.
See the following PHP:
<?php
$query = "INSERT INTO `items` ( `item_field1` , `item_field1` , `item_field1` ) VALUES ( '$value1', '$value2', '$value3')";
// execute query
mysql_query($query);
// get the last auto incremented value
$lastItemID = mysql_insert_id();
?>
For this example, the "items" table has a field "item_id" which is set to auto increment when a new record is entered. You do not need to put "item_id" in the list of fields in the MySQL query although some would prefer to include it in the query (you would insert a NULL for its value).
After executing the MySQL query, you can pass mysql_insert_id() to a variable of your choice and then use this value for whatever you need it for. In some cases, you may be using this ID as a foreign key in another table so you would use $lastItemID, as seen in the example above, within another MySQL INSERT command for a different table.
Related Links
Related Articles / Posts
Controlling PHP Register Globals Using .htaccess File (04/03/2008)
PHP: Include a file and store contents to variable using output buffer (05/06/2007)
PHP Mailer Class - Sending SMTP Email (22/03/2007)
Code Editors (Syntax Highlighting) - Aptana, Crimson Editor, PHP Designer (14/08/2006)
Web Dev News: Pro Ajax and PHP - Building Highly Interactive Applications (Book) (18/07/2006)


