Get the id of AUTO_INCREMENT field after INSERT using php

Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

Get the id of AUTO_INCREMENT field after INSERT using php

Post by Saman » Fri Jul 15, 2011 6:11 pm

If you insert a new value to a MySQL database, and the id is an AUTO_INCREMENT field, this simple function will obtain the id for you without having to do a new query on the database. This is the easiest way to get the id from a newly added row using a MySQL insert query without having to do a second query.

Code: Select all

<?php 

// Do your insert query... 
mysql_query("INSERT etc..."); 

// This finds the id of the row once it has been added... 
$id = mysql_insert_id(); 

// Display it... 
echo $id; 

?>
Post Reply

Return to “PHP & MySQL”