Code has been added to clipboard!
MySQL Last Insert ID for PDO Users
Example
<?php
$host = 'host';
$user = 'user';
$pass = 'pass';
$db = 'db';
try {
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users (username, password, email) VALUES ('Johny', 'Dawkins', '[email protected]')";
// use exec() because no results are returned
$conn->exec($sql);
$latest_id = $conn->lastInsertId();
echo "Insert successful. Latest ID is: " . $latest_id;
} catch(PDOException $e) {
echo $sql . "<br>" . $e->getMessage();Â
}
$conn = null;
?>