How can the LAST_INSERT_ID() function be utilized in PHP to handle database entries?
When inserting data into a database, we often need to retrieve the auto-generated ID of the last inserted row. This can be achieved using the LAST_INSERT_ID() function in MySQL. In PHP, we can execute a query to insert data into the database and then immediately retrieve the last inserted ID using the mysqli_insert_id() function.
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Insert data into the database
$mysqli->query("INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')");
// Get the ID of the last inserted row
$last_insert_id = $mysqli->insert_id;
// Use the last insert ID as needed
echo "Last Inserted ID: " . $last_insert_id;
// Close the connection
$mysqli->close();
Keywords
Related Questions
- What are the best practices for loading and examining external website content in PHP?
- Welche Sicherheitsvorkehrungen sollten getroffen werden, um SQL-Injektionen zu vermeiden, insbesondere bei der Verwendung von Benutzereingaben in SQL-Abfragen?
- How can the array_chunk() function in PHP be used to manipulate arrays for displaying content?