以前使用PDO,只是间接的使用,即在框架中使用,对PDO没有仔细了解过,总感觉很神秘,最近一个项目用到PDO,因为没有使用框架,对PDO的使用有了大致的了解。
其实PDO 就是在php 中操作数据库的一个方法,目前pdo支持12种数据库。首先连接数据库
function mysql_connect(){
try{
static $dbh='';
if(empty($dbh)){
$user='root';
$pass='';
$dbh=new PDO('mysql:host=localhost;dbname=evidence_api',$user,$pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
return $dbh;
}catch (PDOException $exception){
return $exception->getMessage();
}
}
默认PDO不会抛出异常,就是你无法直接获取数据库的错误,所以需要设置一个属性
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
这样就可以通过PDOException 类获取获取具体的sql错误。
pdo支持数据库预处理,其实就是 prepare 和 bindValue 两个函数的使用。通过占位符代替具体的参数,防止sql注入,预编译另一个好处就是一条sql语句可以反复执行。提高sql执行效率。
这是因为在执行一次sql操作时,mysql服务器每次都要进行 sql语法的校验,把sql语句编译成可执行函数,最后执行sql语句。
而预编译后只进行一次语法的校验及编译,下次只需要设置变量即可。
MySQL执行预编译
MySQL执行预编译分为如三步:
l 执行预编译语句,例如:prepare fun from 'select * from t_book where bid=?'
l 设置变量,例如:set @str='b1'
l 执行语句,例如:execute fun using @str
如果需要再次执行fun,那么就不再需要第一步,即不需要再编译语句了:
l 设置变量,例如:set @str='b2'
l 执行语句,例如:execute fun using @str
$sql = "insert into out_evidence(userId,evidence,entrustAgree,applyForm,notaryCount,isExpress,express) value (?,?,?,?,?,?,?)";
try {
$statement = $h->prepare($sql);
$statement->bindValue(1,$body['userId']);
$statement->bindValue(2,json_encode($body['evidence']));
$statement->bindValue(3,$body['entrustAgree']);
$statement->bindValue(4,$body['applyForm']);
$statement->bindValue(5,$body['notaryCount']);
$statement->bindValue(6,$body['isExpress']);
$statement->bindValue(7,json_encode($body['express']));
$res=$statement->execute();
$id = $h->lastInsertId();
} catch (PDOException $exception) {
returnJson(0,
还有一个注意点就是fetchAll 函数,获取到的数据格式可能不是你想要的,一般设置如下格式才是索引数组的格式。
$device_res=$device_res->fetchAll(PDO::FETCH_ASSOC);