PHP MySql INSERT and Return ID
Problem: Using PHP, insert a record into a MySQL database and return the ID for the record inserted. Report on any errors that may occur.
Solution:
$insert_id = null;
try
{
if(!$result = mysql_query('INSERT INTO my_table VALUES(null,"some value here")'))
{
throw new Exception('Query failed');
}
else
{
$insert_id = mysql_insert_id();
}
}
catch (Exception $e)
{
echo $e->getMessage();
}
echo $insert_id;