07 Dec 2013
Get Last Inserted Id
There are many cases where we need AUTO_INCREMENT ID that generated from the previous INSERT operation, we can get that by using mysql_insert_id() function.
Like:-
$con = mysql_connect(“localhost”, “root”, “”);
mysql_select_db(“my_database”,$con);
$query = ”insert into emp (name,salary,phone) values (‘amit’,9000,’9847476744’)”;
mysql_query($query);
echo “Last inserted id is ”. mysql_insert_id();
mysql_select_db(“my_database”,$con);
$query = ”insert into emp (name,salary,phone) values (‘amit’,9000,’9847476744’)”;
mysql_query($query);
echo “Last inserted id is ”. mysql_insert_id();
Some time programmer use “select max(id) from tablename” to get the last inserted id, but it may return wrong result because max(id) may not be last inserted id while transaction going on OR records inserting on.