```
$pdo = new PDO('mysql:host=localhost;dbname=douphp','root','123456');
$sql = 'select * from dou_article';
$smt = $pdo->query($sql);
$rows = $smt->fetchAll(PDO::FETCH_ASSOC);
```
执行,增,改,删:$pdo->exec($sql); 更新一样的则不更新,返回0
设置客户端字符集为utf8:$pdo->exec('set names utf8');
预处理:(不能提高速度,但是可以避免sql注入风险,建议使用)
增删改:
```
$pdo = new PDO('mysql:host=localhost;dbname=douphp','root','123456');
$sql = 'select * from dou_article';
$smt = $pdo->prepare($sql); #预处理sql语句
if($smt->execute()) {
$tot = $smt->rowCount();#返回影响的行数
echo 'successful';
}else {
echo 'error';
}
```
查询:
```
$pdo = new PDO('mysql:host=localhost;dbname=douphp','root','123456');
$sql = 'select * from dou_article';
$smt = $pdo->prepare($sql);
$smt = execute();
$rows = $smt->fetchAll(PDO::FETCH_ASSOC);
pdostatement类:
fetchAll
fetch #获取一行数据
fetchColumn
execute
rowCount
bindValue #预处理绑定值(sql="select ...where id=?")
lastInsertId
setAttribute()//可以在之前设置查询结果集以什么形式返回
$pdo = new PDO('mysql:host=localhost;dbname=douphp','root','123456');
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
```
PDO事物处理:
事务机制:(只有引擎是InnoDB才支持)
beginTransaction():开启任务
commit():成功提交本次任务
rollback():失败撤消本次任务
PDOException:异常处理:
getMessage()
getFile()
getLine()
一次事物机制的案例,同时删除两条数据,如果有一条出错,则退回,都不执行
```
$pdo = new PDO('mysql:host=localhost;dbname=douphp','root','123456');
$pdo->exec('set names utf8');
#修改抛出异常模式,默认为不抛出
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
#开启事物
$pdo->beginTransaction();
try{
#一次删除
$sql = "delete from user where id =1";
$smt=$pdo->prepare($sql);
$smt->execute();
#一次删除
$sql = "delete from user where id =1";
$smt=$pdo->prepare($sql);
$smt->execute();
//没错提交
$pdo->commit();
}catch(PDOException $e) {
echo $e->getMessage();#打印出错误信息
//有错撤回
$pdo->rollBack();
}
```