PDO数据库抽象层
其实也就是说,为了方便PHP项目各种数据库切换的方便以及代码兼容性,再各种数据库上又封装了一层,做成了统一的接口,方便数据库使用和切换。
PDO链接mysql数据库:
<?php
header("Content-type: text/html; charset=utf-8");
$dbms = 'mysql';
$dbName='abc';
$user = 'root';
$pwd = '123456';
$hosts='localhost';
$dsn = "$dbms:host=$hosts;dbname=$dbName";
try{
$pdo = new PDO($dsn ,$user ,$pwd);
echo "PDO 连接 MySql 成功";
}catch(Exception $e){
echo $e->getMessage()."<br>";
}
?>
注意上面的dsn变量:
打开数据库,进入表,把c1列的内容拿出来
<?php
header("Content-type: text/html; charset=utf-8");
$dbms = 'mysql';
$dbName='abc';
$user = 'root';
$pwd = '123456';
$hosts='localhost';
$dsn = "$dbms:host=$hosts;dbname=$dbName";
try{
$pdo = new PDO($dsn ,$user ,$pwd);
$query = "select * from tb_222";
$result = $pdo->prepare($query);
$result->execute();
while($res = $result->fetch(PDO::FETCH_ASSOC)) {
echo $res['c1'] . '<br>';
}
}catch(Exception $e){
echo $e->getMessage()."<br>";
}
?>
5.
把上面的例子改成一起全都取出来,然后在枚举:
<?php
header("Content-type: text/html; charset=utf-8");
$dbms = 'mysql';
$dbName='abc';
$user = 'root';
$pwd = '123456';
$hosts='localhost';
$dsn = "$dbms:host=$hosts;dbname=$dbName";
try{
$pdo = new PDO($dsn ,$user ,$pwd);
$query = "select * from tb_222";
$result = $pdo->prepare($query);
$result->execute();
$res = $result->fetchAll(PDO::FETCH_ASSOC);
for($i = 0 ;$i < count($res) ;$i ++){
echo $res[$i]['c1'].'<br>';
}
}catch(Exception $e){
echo $e->getMessage()."<br>";
}
?>
PDO中事物处理:
还有很多函数,用的时候再查吧,注意PDO里面是支持错误捕获,警告设置,异常模式,错误处理等。