To get the last inserted ID (auto-increment value) after inserting a new row into a MySQL database table using PHP, you can use the mysqli_insert_id() function with mysqli or lastInsertId() method with PDO. These functions/methods return the last generated auto-increment ID from the last INSERT query.
Here's an example using mysqli to insert a new row into the users table and get the last inserted ID:
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
// 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 query to insert data
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id; // Get last inserted ID
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close connection
$conn->close();
Here's the same example using PDO :
// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";
try {
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Data to be inserted
$name = "John Doe";
$email = "john@example.com";
// SQL query to insert data
$sql = "INSERT INTO users (name, email) VALUES (:name, :email)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
// Execute the query
$stmt->execute();
$last_id = $conn->lastInsertId(); // Get last inserted ID
echo "New record created successfully. Last inserted ID is: " . $last_id;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
} finally {
// Close connection
$conn = null;
}
Running these scripts will insert a new row into the users table, and then it will display the last inserted ID. This ID is useful for scenarios where you need to reference the newly inserted row in subsequent database operations.