mysql只有这个InnoDB驱动是支持事务处理的,默认MyIsAM驱动不支持,如果使用使用请注意更改驱动
class psd{
public function db(){
$dsn = 'mysql:host=localhost;dbname=test';
$user = 'root';
$password = 'root';
//连接数据库
try{
$dsh = new PDO($dsn,$user,$password,array(PDO::ATTR_PERSISTENT => true));
}catch (PDOException $e){
echo "连接数据库失败".$e->getMessage();
}
//实现查询
$res = $dsh->query("select * from user");
$res ->setFetchMode(PDO::FETCH_ASSOC); //获取模式为每行按字段名索引的数组
$result_arr=$res->fetchAll();
Print_r($result_arr);
//实现插入
try{
$dsh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dsh->beginTransaction();
$dsh->exec("insert into user (name,age)values('hello','13')");
$dsh->exec("insert into user (name,age)values('ally','15')");
$dsh->commit();
}catch (PDOException $e){
$dsh->rollBack();
echo $e->getMessage();
}
$dsh->exec("delete from user WHERE id in(41,42,43,44)");
//预处理ok
$stmt = $dsh->prepare("insert into user (username,age) VALUES (?,?)");
$stmt->bindParam(1,$username);
$stmt->bindParam(2,$age);
$username = 'onece';
$age =14;
$stmt->execute();
$username = 'onece';
$age =14;
$stmt->execute();
}
}
调用
$a = new psd();
$a->db();