PHP: PDO transaction
嘻嘻发布于2020-03-30
浏览这是一个关于如何在PHP中使用PDO对象的事务例子,所有操作要么都执行成功,要么不执行,在某些场景中必须要用到事务。
例子:
/**
* 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=test', 'root', '', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
));
//We are going to assume that the user with ID #1 has paid 10.50.
$userId = 1;
$paymentAmount = 10.50;
//We will need to wrap our queries inside a TRY / CATCH block.
//That way, we can rollback the transaction if a query fails and a PDO exception occurs.
try{
//We start our transaction.
$pdo->beginTransaction();
//Query 1: Attempt to insert the payment record into our database.
$sql = "INSERT INTO payments (user_id, amount) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
$userId,
$paymentAmount,
)
);
//Query 2: Attempt to update the user's profile.
$sql = "UPDATE users SET credit = credit + ? WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
$paymentAmount,
$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();
}
说明:
交易条款说明。
快速解释一些关键术语:
beginTransaction:启动事务,并且禁用MySQL的默认自动提交特性。例如:如果您运行一个INSERT查询,数据将不会被直接插入。
commit:当你提交一个事务时,你基本上是在告诉MySQL一切正常,你的查询结果是最终的。
rollBack:当您回滚一个事务时,您基本上是在告诉MySQL您不希望提交更改。这通常在查询失败时使用。