// create a new PDO database connection $pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password'); // prepare an INSERT statement and execute it $stmt = $pdo->prepare('INSERT INTO users (name, email) VALUES (?, ?)'); $stmt->execute(['John Doe', 'johndoe@example.com']); // retrieve the ID of the last inserted record $lastId = $pdo->lastInsertId(); echo 'Last inserted ID: ' . $lastId;
// create a new PDO database connection $pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password'); // begin a transaction $pdo->beginTransaction(); try { // prepare and execute multiple INSERT statements within the same transaction $stmt1 = $pdo->prepare('INSERT INTO products (name, price) VALUES (?, ?)'); $stmt1->execute(['Book', 10.99]); $stmt2 = $pdo->prepare('INSERT INTO orders (product_id, quantity) VALUES (?, ?)'); $stmt2->execute([$pdo->lastInsertId(), 3]); // commit the transaction $pdo->commit(); echo 'Order placed successfully!'; } catch (Exception $e) { // rollback the transaction and display error message $pdo->rollBack(); echo 'Error placing order: ' . $e->getMessage(); }In both examples, we create a PDO database connection and execute an INSERT statement to add a new record to a table. After the statement is executed, we retrieve the ID of the last inserted record using the lastInsertId function and display it on the screen. The package library used for this example is PDO, which is a database abstraction layer that provides a consistent API for accessing and manipulating different types of databases.