If you perform an insert into a mysql database table containing an AUTO_INCREMENT field, you can retrive the ID of the last inserted record without execute any query.

Let’s start with an example.

In your MySQL DB create a new table as follows:

CREATE TABLE table(
id INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
field1 INT (11) NOT NULL,
field2 INT (11) NOT NULL,
)

PHP

Now, write a simple PHP script:
<?php
// section 1
//setting up DB parameter
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "yourDB";

// section 2
// Create the connection with the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection with the database

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// section 3 insert a new record
$sql = "INSERT INTO table(field1, field2) VALUES (10, 11)";
$last_inserted_id = 0;
if ($conn->query($sql) === TRUE)
{
// retrieve the last inserted ID
$last_inserted_id = $conn->insert_id;
} else {
// if there was an error
echo "Error: " .$conn->error;
die();
}
echo "New record created with ID: " . $last_inserted_id;
$conn->close();
?>

Section 1 sets up the DB parameters

Section 2 creates the connection with the DB using the parameters specified in Section 1

Section 3 inserts  new record in the DB and retrieve the last inserted id, if the INSERT statement successes.

Gg1