Skip navigation.

Contridentuallity

Not a fact, a theory!?

Posts tagged with "mysql_insert_id()"

MySQL Last Inserted ID

, , , ...

In some cases, you will need to retrieve the last inserted ID which was inserted into your database using PHP specifically when you are using an 'auto_increment' parameter for that field. Obviously there is a common way of doing this, but there is also a built in function which will help you to achieve the same result with less code.

The common way :
$query = "INSERT INTO table (id, value) VALUES ('', 'value')";
mysql_query($query) or die(mysql_error());

$id = mysql_result((mysql_query("SELECT * FROM table WHERE value = 'value'")), 0, 'id');

echo "The last inserted ID was :" . $id;


The easy way :
$query = "INSERT INTO table (id, value) VALUES ('', 'value')";
mysql_query($query) or die(mysql_error());

echo "The last inserted ID was :" . mysql_insert_id();


A useful snippet if you aren't familiar with the 'mysql_insert_id()' function. This will save you some coding and time if you've been using other common, longer ways in the past.
Download Opera, the fastest and most secure browser
December 2009
S M T W T F S
November 2009January 2010
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31