$pdo=newPDO(
$dsn,
$username,
$password,
array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION)
);
try {
$statement=$pdo->prepare("UPDATE user SET name = :name");
$pdo->beginTransaction();
$statement->execute(["name"=>'Bob']);
$statement->execute(["name"=>'Joe']);
$pdo->commit();
}
catch (\Exception$e) {
if ($pdo->inTransaction()) {
$pdo->rollback();
// If we got here our two data updates are not in the database
}
throw$e;
}
// In this example we are using MySQL but this applies to any database that has support for transactions$db=newPDO('mysql:host='.$host.';dbname='.$dbname.';charset=utf8', $username, $password);
// Make sure that PDO will throw an exception in case of error to make error handling easier$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
// From this point and until the transaction is being committed every change to the database can be reverted$db->beginTransaction();
// Insert the metadata of the order into the database$preparedStatement=$db->prepare(
'INSERT INTO `orders` (`order_id`, `name`, `address`, `created_at`)
VALUES (:name, :address, :telephone, :created_at)'
);
$preparedStatement->execute([
'name'=>$name,
'address'=>$address,
'telephone'=>$telephone,
'created_at'=>time(),
]);
// Get the generated `order_id`$orderId=$db->lastInsertId();
// Construct the query for inserting the products of the order$insertProductsQuery='INSERT INTO `orders_products` (`order_id`, `product_id`, `quantity`) VALUES';
$count=0;
foreach ( $productsas$productId=>$quantity ) {
$insertProductsQuery.=' (:order_id'.$count.', :product_id'.$count.', :quantity'.$count.')';
$insertProductsParams['order_id'.$count] =$orderId;
$insertProductsParams['product_id'.$count] =$productId;
$insertProductsParams['quantity'.$count] =$quantity;
++$count;
}
// Insert the products included in the order into the database$preparedStatement=$db->prepare($insertProductsQuery);
$preparedStatement->execute($insertProductsParams);
// Make the changes to the database permanent$db->commit();
}
catch ( PDOException $e ) {
// Failed to insert the order into the database so we rollback any changes$db->rollback();
throw$e;
}
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems
resetting your password contact us
Check Your Email and Click on the link sent to your email