PDO综合实例应用
2016-08-14 17:24
85 查看
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 4000 $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']; ?>
相关文章推荐
- JDBC操作数据库――CRUD综合应用实例
- 《有博天天读》Silverlight中InkPresenter控件综合应用实例
- js综合应用实例简单的表格统计
- jquery综合应用实例
- SQL 综合应用(1.创建临时表,为后续查询所用) 实例_(学生,课程表,选修表)
- UISegmentedControl ,UIStepper,UISwitch,UISlider综合应用(实例需求)
- C++ 容器的综合应用的一个简单实例——文本查询程序
- SQL 综合应用(2.数据控制) 实例_(学生,课程表,选修表)
- 第三十讲 : 综合应用&存储过程 返回值参数实例
- XML数据岛的综合应用实例
- Java回调以及线程综合应用实例--陆续添加
- cut、file、for、ls、的综合应用实例
- C++ 容器的综合应用的一个简单实例——文本查询程序
- Linux C编程--进程间通信(IPC)6--综合应用实例--信号量和共享内存的使用
- 深入浅出VC++串口编程(六) 综合实例之短信应用开发
- SQL Server 应用开发 --- SQL SERVER 2000 数据查询综合实例
- Linux C编程--进程介绍7--综合应用实例
- VisualNet图形化的电力综合布线管理系统的应用实例展示
- LinQ综合应用实例
- ext2.0树控件综合应用实例