What is the function mysql_insert_id() in PHP and how can it be used to retrieve the ID of a newly inserted database entry?
The function mysql_insert_id() in PHP is used to retrieve the ID of the last inserted row in a MySQL database. This can be useful when you need to get the auto-generated ID of a newly inserted entry for further processing or referencing. To use mysql_insert_id(), you simply call the function after executing an INSERT query in your PHP code.
// Execute INSERT query
$query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
$result = mysqli_query($connection, $query);
// Get the ID of the newly inserted row
$new_id = mysqli_insert_id($connection);
// Use the new ID for further processing
echo "The ID of the newly inserted row is: " . $new_id;
Related Questions
- What common syntax errors should PHP developers be aware of when creating SQL queries?
- What are some common pitfalls to avoid when using PHP for form submission and email handling?
- How can .htaccess be utilized to improve URL structure in PHP applications and what are the best practices for implementing these changes?