How to Get last id From Mysql Using PHP

How to Get last id From Mysql Using PHP

In this article, you will learn How to Get the last id From Mysql Using PHP. Get the last id from tables using the below example.

Example:-

db.php

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
$connection = mysqli_connect($servername, $username, $password, $dbname);
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}
?>

index.php

<?php
$sql = "INSERT INTO record (firstname, lastname, email) VALUES ('Deepak', 'Kumar', 'huboftutorials@gmail.com')";
if (mysqli_query($connection, $sql)) {
    $last_id = mysqli_insert_id($connection);
    echo "New record inserted successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($connection);
?>

1 Comment

  • Lucy

    September 11, 2020 - 7:03 pm

    This is my first time visit at here and i am actually impressed to
    read everthing at single place.

Leave A Reply