How does the function mysql_insert_id() work in PHP and what is its main purpose?
The function mysql_insert_id() in PHP returns the ID generated by a query on a table with an AUTO_INCREMENT column. Its main purpose is to retrieve the last inserted ID in a database table after an INSERT query has been executed. This can be useful for tasks such as linking related data in different tables or redirecting users to a newly created resource.
// Connect to the database
$conn = mysqli_connect("localhost", "username", "password", "database");
// Perform an INSERT query
mysqli_query($conn, "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");
// Get the last inserted ID
$last_insert_id = mysqli_insert_id($conn);
// Use the last inserted ID for further operations
echo "Last inserted ID: " . $last_insert_id;