Transakcje PDO PHP
Jest to tutorial dotyczący korzystania z transakcji za pomocą PDO w PHP. Transakcje są przydatne wtedy gdy chcemy wykonać wiele powiązanych ze sobą zapytań. W niektórych scenariuszach możesz chcieć upewnić się, że wszystkie kwerendy zostały pomyślnie wykonane przed zatwierdzeniem zmian w bazie danych. Na przykład: Drugie zapytanie nie powinno zostać wykonane, jeśli pierwsze zapytanie zakończy się niepowodzeniem.
<?php
/**
* Connect to MySQL and instantiate the PDO object.
* Set the error mode to throw exceptions and disable emulated prepared statements.
*/
$pdo = new PDO('mysql:host=localhost;dbname=nazwa_bazy', 'user', 'pass', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
));
$userId = 1;
$amount = 100;
//We start our transaction.
$pdo->beginTransaction();
try{
//Query 1: Attempt to insert the payment record into our database.
$sql = "INSERT INTO payments (user_id, amount) VALUES (:user_id, :amount)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':user_id' => $userId,
':amount' => $amount,
)
);
//Query 2: Attempt to update the user's profile.
$sql = "UPDATE users SET paymentsum = paymentsum + :amount WHERE id = :user_id";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':amount' => $amount,
':user_id' => $userId
)
);
//We've got this far without an exception, so commit the changes.
$pdo->commit();
}
//Our catch block will handle any exceptions that are thrown.
catch(Exception $e){
//An exception has occured, which means that one of our database queries
//failed.
//Print out the error message.
echo $e->getMessage();
//Rollback the transaction.
$pdo->rollBack();
}
