Skip to content
PHP Logo

How does the timing of executing mysql_query affect the value returned by mysql_insert_id in PHP?

When using `mysql_insert_id` in PHP to retrieve the ID generated by an AUTO_INCREMENT column in a table, it is important to execute the query immediately after the INSERT query to ensure the correct ID is returned. If there are other queries executed between the INSERT query and calling `mysql_insert_id`, the value returned may not be accurate. To solve this issue, make sure to call `mysql_insert_id` immediately after the INSERT query.

php
// Execute the INSERT query
mysql_query("INSERT INTO table_name (column_name) VALUES ('value')");

// Get the ID generated by the INSERT query
$id = mysql_insert_id();