1. query(), fetch(), fetchAll(), rowCount(), exec()综合应用
<?php
$dsn="mysql:host=localhost;dbname=guestbook";
$db=new PDO($dsn,'root','123'); //连接数据库
$db->query('set names utf-8');
$affected=$db->exec("update lyb set content='用PDO修改记录' where ID=2014211253"); //exec()返回受影响的记录数
echo "<p>共有".$affected."行记录被修改</p>";
$result=$db->query('select * from lyb');
$result->setFetchMode(PDO::FETCH_ASSOC); //设置fetch()方法为关联数组
var_dump($result); //与mysql不同的是,结果集返回的是对象类型,而mysql是资源类型
echo "<br /><br />";
print_r($row=$result->fetch()); //可以在函数内加参数,默认混合数组,(1或2)关联数组,3索引数组
echo "<br />共有".$result->rowCount()."行<br /><br />";
$row_dim2=$result->fetchAll(); //读取所有记录到二维数组$row_dim2中
foreach ($row_dim2 as $row) { //将每条记录放到数组$row中
print_r($row); //依次打印每条记录
echo "<br />";
}
?>
2. 使用prepare()方法执行预处理语句
2.1 插入
<?php
$dsn="mysql:host=localhost;dbname=guestbook";
$db=new PDO($dsn,'root','123',array(PDO::ATTR_PERSISTENT=>true)); //长连接
$db->query('set names utf-8');
$sql="insert into lyb(title,content,author) values(?,?,?)";
//用?作占位符,等价于 $sql="insert into lyb(title,content,author) values(:title,:content,:author);
$stmt=$db->prepare($sql); //返回一个查询对象,准备执行查询
$title='PDO预处理'; $content='这是插入的记录'; $author='bingo';
$stmt->bindParam(1,$title); //绑定参数,等价于 $stmt->bindParam(':title',$title);
$stmt->bindParam(2,$content);
$stmt->bindParam(3,$author);
$stmt->execute(); //【执行语句】,将插入一条记录
#可以用该句话代替上面五句话 $stmt->execute(array('PDO预处理','这是插入的记录','bingo'));
echo "新插入记录的ID号是:".$db->lastInsertId();
# 如果要再插入记录,只要添加下面的代码即可
$title='第二条'; $content='这是另一条插入的记录'; $author='ognib';
$stmt->execute();
echo "<br />新插入记录的ID号是:".$db->lastInsertId();
?>
2.2 查询
<?php
$dsn="mysql:host=localhost;dbname=guestbook";
$db=new PDO($dsn,'root','123'); //连接数据库
$db->query('set names utf-8');
$sql='select * from lyb where title like ?'; //【注意】不能写成%?%的形式,因为占位符必须用于整个值的位置
$stmt=$db->prepare($sql); //创建一个查询对象,准备执行语句
$title='哈';
$stmt->execute(array("%$title%")); //执行查询的时候同时绑定数组,execute()中的参数是一个数组
$row=$stmt->fetch(1); //以关联数组的形式将结果集中的[第一条]记录取出
echo "<br /><br />";
var_dump($row); //输出数组
echo "<br /><br />".$row['title'];
?>
转载请注明原文地址: https://ju.6miu.com/read-1298313.html