php PDO实现的事务回滚示例

时间:2022-08-26 15:15:36

本文实例讲述了php PDO实现的事务回滚。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$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','yexianming@163.com')");
  $conn->exec("INSERT INTO `hello`(`firstname`,`lastname`,`email`)VALUES('YE','CONG','yecong@163.com')");
  $conn->exec("INSERT INTO `hello`(`firstname`,`lastname`,`email`)VALUES('FANG','MENG','fangmeng@168.com')");
  //提交事务
  $conn->commit();
  echo "New records created successfully!";
}catch(PDOException $e){
   //回滚事务
   $conn->rollBack();
   echo $sql."<br>".$e->getMessage();
}
$conn=NULL;

希望本文所述对大家PHP程序设计有所帮助。