PHP MySQL Get Last Inserted ID

Retrieving the last auto-generated ID of a row that was inserted into a MySQL table using PHP involves using the mysqli_insert_id() function. Here’s an example of how to retrieve the last inserted ID using PHP:

<?php
// MySQL server configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
// Create a connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
// Insert data into the table
$sql = "INSERT INTO users (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";
if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    echo "Data inserted successfully with ID: " . $last_id;
} else {
    echo "Error inserting data: " . mysqli_error($conn);
}
// Close the connection
mysqli_close($conn);
?>

In this example, we first define the configuration for the MySQL server by specifying the server name, username, and password. We also specify the name of the database we want to work with in the $dbname variable. We then create a connection to the server and select the appropriate database using the mysqli_connect() function.

Next, we define the data we want to insert into the table in the $sql variable using SQL syntax. In this example, we insert a new row of data into a table called “users” with values for the firstname, lastname, and email columns.

We then execute the SQL query using the mysqli_query() function and check if it was successful. If it was successful, we retrieve the last inserted ID using the mysqli_insert_id() function and store it in a variable called $last_id. We then print a message indicating that the data was inserted successfully, along with the last inserted ID.

Finally, we close the connection using the mysqli_close() function.