Sunday, September 2, 2012

Getting Mysql Auto Increment ID After Insert

I usually put the ID field of my table in MYSQL to Auto Increment , It will generate a unique id for the ID field in the row and i use the ID as primary key.
So those people use this might need the value of auto generated number after doing the insert! The mysql_insert_id will return the value of ID generated by AutoIncerement .

!!! Remember to run this command immediately after the insert command because it return the last inserted id that generated by auto inc.
!!! In case of fail in insert command it will return 0.


$conn = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$conn) {
    die('Could not connect: ' . mysql_error());

mysql_query("INSERT INTO mytable (name) values ('')");
echo("Last inserted record has id %d\n", mysql_insert_id());

Social Networks Sharing