$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)"); $stmt->execute([$name, $email]); $user_id = $pdo->lastInsertId();
$dbh = new PDO('mysql:host=localhost;dbname=example', $user, $pass); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $dbh->prepare("INSERT INTO products (name, price) VALUES (?, ?)"); $stmt->execute([$name, $price]); $product_id = $dbh->lastInsertId();In this example, we are using PDO to connect to a MySQL database and inserting a new product into a table. We then retrieve the newly created ID with the lastInsertId method and use it for further operations. The lastInsertId method is part of the PDO package library in PHP.