how to get id of last inserted row in mysql php code example
Example 1: get last inserted id in php
Example (MySQLi Procedural)
$last_id = mysqli_insert_id($conn);
Example 2: get id of record created php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Example 3: find last id
//laravel controller
$newOrder = new Order();
...
...
$newOrder->save();
$last_id = $newOrder->id;