PDO
程序员文章站
2022-04-22 13:52:40
...
一、创建一个PDO对象
try{
$pdo = new PDO(“mysql:host=localhost;dbname=pdo”, “root”, “root”);
}
catch (PDOException) {
throw $e;
}
二、设置PDO错误提示级别
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
三、PDO执行语句
$sql = “select * from test”;
$res = pdo−>query( pdo -> query(pdo−>query(sql);
四、PDO获取数据语句
$arr = $res -> fetchAll(PDO::FETCH_ASSOC);
或者
arr=[];while( arr = [];while(arr=[];while(row = $res -> fetch(PDO::FETCH_ASSOC)) {
$arr[] = $row
}
五、PDO预编译
预编译插入数据
使用问号作为占位符,如:
$sql = “insert into test values (?, ?)”
$stmt = pdo−>prepare( pdo -> prepare(pdo−>prepare(sql);
$stmt -> execute(array(1, “Lex”));
或者
$sql = “insert into test values(?, ?)”;
$stmt = pdo−>prepare( pdo -> prepare(pdo−>prepare(sql);
$stmt -> bindParam(1, 1);
$stmt -> bindParam(2, “Lex”);
$stmt -> execute();
使用命名参数作为占位符
$sql = "insert into test values(:id, :name);
$stmt = pdo−>prepare( pdo -> prepare(pdo−>prepare(sql);
$stmt -> execute(array(‘id’ => 1, ‘name’ => ‘Lex’));
或者
$sql = “insert into test values(:id, :name)”;
$stmt = pdo−>prepare( pdo -> prepare(pdo−>prepare(sql);
$stmt -> bindParam(’:id’, 1);
$stmt -> bindParam(’:name’, ‘Lex’);
$stmt -> execute()
预编译查询数据
$sql = “select * from test”;
$stmt = pdo−>prepare( pdo -> prepare(pdo−>prepare(sql);
$stmt -> execute();
$res = $stmt -> fetchAll();
或者
$sql = “select * from test”;
$stmt = pdo−>prepare( pdo -> prepare(pdo−>prepare(sql);
$stmt -> execute();
arr=[];while( arr = [];while(arr=[];while(row = $stmt -> fetch(PDO::FETCH_ASSOC)) {
$arr[] = $row;
}
六、PDO事务处理
try {
$pdo = new PDO(“mysql:host=localhost;dbname=pdo”);
}
catch (PDOException $e) {
die("Connection failed! ". $e -> getMessage());
}
$pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$pdo -> beginTransaction();
$sql = “insert into test values (?, ?)”;
$stmt = pdo−>prepare( pdo -> prepare(pdo−>prepare(sql);
$stmt -> execute(array(1, “Lex”));
$stmt -> execute(array(2, “Venus”));
}
catch (PDOException $e) {
$e -> getMessage();
$pdo -> rollback();
}
上一篇: 文本超出隐藏