How to Get the Last Insert Id in PHP MySQL?

03-Apr-2023

.

Admin

How to Get the Last Insert Id in PHP MySQL?

Hi Dev,

This tutorial is focused on how to get the last insert id in a PHP MySQL. you'll learn how to find the last insert id in PHP MySQL. We will use how to get the last insert id in PHP MySQL. if you have a question about how to get the last insert id in the PHP MySQL then I will give a simple example with a solution.

Now, let's see the article on how to get the last insert id in the PHP MySQL. it's a simple example of how to get the last insert id in PHP MySQL. you can understand the concept of how to find the last insert id in PHP MySQL. if you have a question about how to get the last insert id in a PHP MySQL then I will give a simple example with a solution.

Example:


index.php

<?php

$servername = "localhost";

$username = "root";

$password = "root";

$dbname = "myDB";

// Create a connection

$conn = mysqli_connect($servername, $username, $password, $dbname);

// Check the connection

if (!$conn) {

die("Connection failed: " . mysqli_connect_error());

}

$sql = "INSERT INTO students (firstname, lastname, email)

VALUES ('John','Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {

$last_id = mysqli_insert_id($conn);

echo "Last inserted ID is: " . $last_id;

} else {

echo "Error: " . $sql . "<br>" . mysqli_error($conn);

}

mysqli_close($conn);

?>

Output:

The last inserted ID is: 2

I hope it could help you...

#PHP