学习KING老师的总结一些笔记供以后复习巩固,先要在数据库创建一张有id,username,password,age字段的student数据表
PDO的预处理流程
(1) $pdo->exec() //返回受影响的记录条数,不支持select语句
<?php
header('content-type:text/html;charset=utf-8');
try{
$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '199486';
$pdo = new PDO($dsn,$username,$password);
//数据库的连接信息
$sql = "INSERT student(username,password,age)VALUES('deng','88888',44)";
$res = $pdo->exec($sql);
//返回受影响记录条数
var_dump($res);
}catch(PDOException $e){
echo $e->getMessage();
}
?>
(2) $stmt = $pdo->query($sql); 执行一条SQL语句,返回一个PDOStatement对象
<?php
header('content-type:text/html;charset=utf-8');
try{
$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '199486';
$pdo = new PDO($dsn,$username,$password);
$sql = "SELECT username,password,age FROM student";
$stmt = $pdo->query($sql);
foreach ($stmt as $row){
print_r($row);
echo '<br/>';
}
}catch(PDOException $e){
echo $e->getMessage();
}
?>
得到的结果为一个关联加索引的数组
Array
(
[username] => weiwei
[0] => weiwei
[password] => 199486
[1] => 199486
[age] => 22
[2] => 22
)
(3) fetch() //得到结果集中的一条记录
里面可放入几种可选参数来筛选返回的数组类型及是否为对象
- PDO::FETCH_ASSOC 返回关联数组*
- PDO::FETCH_NUM 返回索引数组
- PDO::FETCH_BOTH 两种数组
- PDO::FETCH_OBJ 返回对象
$stmt = $pdo->prepare($sql); // 准备要执行的SQL语句,返回PDOStatement对象
$res = $stmt->execute() //执行一条预处理语句
<?php
header('content-type:text/html;charset=utf-8');
try{
$dsn = 'mysql:host=localhost;dbname=test';
$username = 'root';
$password = '199486';
$pdo = new PDO($dsn,$username,$password);
$sql = "SELECT * FROM student";
$stmt = $pdo->prepare($sql);
$res = $stmt->execute();
if($res){
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
print_r($row);
echo '<hr/>';
}
}
}catch(PDOException $e){
echo $e->getMessage();
}
?>