PHP 数据库抽象层pdo
PDO是PHP数据对象(PHP Data Object)的缩写。
pdo就是一个“数据库访问抽象层”,作用是统一各种数据库的访问接口,能够轻松地在不同数据库之间进行切换,使得数据库间地移植容易实现。
pdo自带事务功能,并且可以防止sql注入。
PDO
//1.访问不同的数据库
//2.自带事务功能
//3.防止SQL注入
/*//1.造对象
$dsn = "mysql:dbname=mydb;host=localhost";
$pdo = new PDO($dsn,"root","123");
//2.写SQL语句
$sql = "update nation set name='兽族' where code='n013'";
//3.执行SQL语句
//$r = $pdo->query($sql);
$r = $pdo->exec($sql);*/
//事务功能
//造对象
$dsn = "mysql:dbname=mydb;host=localhost";
$pdo = new PDO($dsn,"root","123");
//设置异常模式
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
//写SQL语句
$sql1 = "insert into nation values('n016','人族')";
$sql2 = "insert into nation values('n017','不死族')";
//执行两条SQL语句
try
{
//启动事务
$pdo->beginTransaction();
$pdo->exec($sql1);
$pdo->exec($sql2);
//提交事务
$pdo->commit();
}
catch(PDOException $e)
{
//$e->getMessage();
//回滚
$pdo->rollBack();
}
//造对象
$dsn = "mysql:dbname=mydb;host=localhost";
$pdo = new PDO($dsn,"root","123");
//写SQL语句,预处理语句
$sql = "insert into nation values(?,?)";
//准备SQL语句,返回statement对象
$st = $pdo->prepare($sql);
//绑定参数
/*$st->bindParam(1,$code);
$st->bindParam(2,$name);
$code="n022";
$name="矮人族";*/
$attr = array("n023","魔族");
//提交执行,不用给SQL语句了,已经传过去了
var_dump($st->execute($attr));
//预处理语句里面用?占位的,给数组的时候要给索引数
//造对象
$dsn = "mysql:dbname=mydb;host=localhost";
$pdo = new PDO($dsn,"root","123");
//写SQL语句,预处理语句
$sql = "select * from nation";
//准备执行
$st = $pdo->prepare($sql);
//执行
$st->execute();
//读数据
var_dump($st->fetchAll(PDO::FETCH_ASSOC));