WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP Get ID of Last Inserted Record


Get ID of The Last Inserted Record

INSERT or UPDATE on a table with an AUTO_INCREMENT field

In the table "MyGuests", the "id" segment is an AUTO_INCREMENT field:

Make TABLE MyGuests (
id INT5) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
school VARCHAR(30) NOT NULL,
home VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)

Example (MySQLi Object-oriented)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

//Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
/Check connection
in the event that ($conn->connect_error) {
    die("Connection fizzled: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
Qualities ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
    reverberation "New record made effectively. Last embedded ID is: " . $last_id;
} else {
    reverberation "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Example (MySQLi Procedural)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

//Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
/Check connection
in the event that (!$conn) {
    die("Connection fizzled: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
Qualities ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    reverberation "New record made effectively. Last embedded ID is: " . $last_id;
} else {
    reverberation "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

Example (PDO)

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    /set the PDO blunder mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    Qualities ('John', 'Doe', 'john@example.com')";
   /use executive() on the grounds that no results are returned
    $conn->exec($sql);
    $last_id = $conn->lastInsertId();
    reverberation "New record made effectively. Last embedded ID is: " . $last_id;
    }
catch(PDOException $e)
    {
    reverberation $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>