PHP MySQL Get Last Inserted ID
To get the last inserted ID after inserting a record into a MySQL database using PHP, you can use the mysqli_insert_id() function in MySQLi or the lastInsertId() method in PDO.
Here's how to do it for both approaches:
Using MySQLi:
<?php // MySQLi Configuration $servername = "localhost"; // Change this to your MySQL server address $username = "username"; // Change this to your MySQL username $password = "password"; // Change this to your MySQL password $database = "dbname"; // Change this to your MySQL database name // Create connection $conn = new mysqli($servername, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // Data to be inserted $name = "John Doe"; $email = "john@example.com"; // SQL statement $sql = "INSERT INTO users (name, email) VALUES (?, ?)"; // Prepare and bind the statement $stmt = $conn->prepare($sql); $stmt->bind_param("ss", $name, $email); // Execute the statement if ($stmt->execute()) { // Get the last inserted ID $last_id = $conn->insert_id; echo "New record created successfully. Last inserted ID is: " . $last_id; } else { echo "Error: " . $sql . "You can click on above box to edit the code and run again.
" . $conn->error; } // Close connection $stmt->close(); $conn->close(); ?>
Output
Using PDO:
<?php // PDO Configuration $servername = "localhost"; // Change this to your MySQL server address $username = "username"; // Change this to your MySQL username $password = "password"; // Change this to your MySQL password $database = "dbname"; // Change this to your MySQL database name // Data to be inserted $name = "John Doe"; $email = "john@example.com"; try { // Connect to MySQL using PDO $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password); // Set PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // SQL statement $sql = "INSERT INTO users (name, email) VALUES (:name, :email)"; // Prepare the statement $stmt = $conn->prepare($sql); // Bind parameters $stmt->bindParam(':name', $name); $stmt->bindParam(':email', $email); // Execute the statement $stmt->execute(); // Get the last inserted ID $last_id = $conn->lastInsertId(); echo "New record created successfully. Last inserted ID is: " . $last_id; } catch(PDOException $e) { echo "Error: " . $e->getMessage(); } // Close connection $conn = null; ?>You can click on above box to edit the code and run again.