Page 1 of 1

Get the id of AUTO_INCREMENT field after INSERT using php

Posted: Fri Jul 15, 2011 6:11 pm
by Saman
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; 

?>