php事务回滚简单实现方法示例

作者:袖梨 2022-06-24
 
 代码如下复制代码
$servername="localhost";
$username="root";
$password="admin";
$dbname="test";
try{
  $conn=new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
  $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
  //开始事务
  $conn->beginTransaction();
  $conn->exec("INSERT INTO `hello`(`firstname`,`lastname`,`email`)VALUES('YE','XIAMING','[email protected]')");
  $conn->exec("INSERT INTO `hello`(`firstname`,`lastname`,`email`)VALUES('YE','CONG','[email protected]')");
  $conn->exec("INSERT INTO `hello`(`firstname`,`lastname`,`email`)VALUES('FANG','MENG','[email protected]')");
  //提交事务
  $conn->commit();
  echo "New records created successfully!";
}catch(PDOException $e){
   //回滚事务
   $conn->rollBack();
   echo $sql."
"
.$e->getMessage();
}
$conn=NULL;
 

相关文章

精彩推荐