PDO 学习与使用 ( 二 ) PDO 数据提取 和 预处理语句
以数据库 msg 为例,说明 PDO 的数据提取、预处理语句:
mysql> show tables;
+---------------+
| Tables_in_msg |
+---------------+
| message |
+---------------+
mysql> show create table message \G
*************************** 1. row ***************************
Table: message
Create Table: CREATE TABLE `message` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` varchar(200) NOT NULL COMMENT '聊天内容',
`flag` int(11) NOT NULL DEFAULT '0' COMMENT '0-未读 1-已读',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
mysql> show columns from message;
+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| content | varchar(200) | NO | | NULL | |
| flag | int(11) | NO | | 0 | |
+---------+--------------+------+-----+---------+----------------+
mysql> select * from message;
+----+---------+------+
| id | content | flag |
+----+---------+------+
| 1 | hello | 1 |
| 2 | world | 1 |
+----+---------+------+
从表中选择数据
<?php$dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$stmt = $db_conn->query('select * from message'); while($row = $stmt->fetch()) {echo $row['id'],'.',$row['content'],'<br />'; }
返回:
1.hello
2.world
说明:
① $db_conn 是 PDO 对象
② $stmt 是 PDOStatement 对象,它代表查询,并获取结果(stmt 有预处理的意思)
③ PDOStatement::fetch() 方法可以 处理大量提取数据的模式
④ fetch() 方法将从结果集中取出一行数据
数据提取模式
fetchAll() 方法可以一次检索所有的行。同时 fetch() 方法 和 fetchAll() 方法 都可以接受 fetch_style 参数,包括:
PDO::FETCH_ASSOC,返回关联数组
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$stmt = $db_conn->query('select * from message');$res = $stmt->fetch(PDO::FETCH_ASSOC);var_dump($res);
返回:
array'id' => string '1' (length=1)'content' => string 'hello' (length=5)'flag' => string '1' (length=1)
或(fetchAll):
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$stmt = $db_conn->query('select * from message');$res = $stmt->fetchAll(PDO::FETCH_ASSOC);var_dump($res);
返回:
array0 => array'id' => string '1' (length=1)'content' => string 'hello' (length=5)'flag' => string '1' (length=1)1 => array'id' => string '2' (length=1)'content' => string 'world' (length=5)'flag' => string '1' (length=1)
PDO::FETCH_NUM,返回索引数组:
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$stmt = $db_conn->query('select * from message');$res = $stmt->fetchAll(PDO::FETCH_NUM);var_dump($res);
返回:
array0 => array0 => string '1' (length=1)1 => string 'hello' (length=5)2 => string '1' (length=1)1 => array0 => string '2' (length=1)1 => string 'world' (length=5)2 => string '1' (length=1)
PDO::FETCH_BOTH,返回关联数组和索引数组:
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$stmt = $db_conn->query('select * from message');$res = $stmt->fetchAll(PDO::FETCH_BOTH);var_dump($res);
返回:
array0 => array'id' => string '1' (length=1)0 => string '1' (length=1)'content' => string 'hello' (length=5)1 => string 'hello' (length=5)'flag' => string '1' (length=1)2 => string '1' (length=1)1 => array'id' => string '2' (length=1)0 => string '2' (length=1)'content' => string 'world' (length=5)1 => string 'world' (length=5)'flag' => string '1' (length=1)2 => string '1' (length=1)
参数和预处理语句
提取 id = 1 的 message 的信息,要使用一个 预处理语句,告诉 MySQL 这条语句的哪些部分是变量。在运行 PDO::query() 时,组合了 预处理 和 执行步骤:
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$sql = 'select * from message where id = :msg_id'; $stmt = $db_conn->prepare($sql);//执行预处理 $stmt->execute(array('msg_id'=>2)); $res = $stmt->fetchAll(PDO::FETCH_ASSOC);var_dump($res);
返回:
array0 => array'id' => string '1' (length=1)'content' => string 'hello' (length=5)'flag' => string '1' (length=1)
说明:
① 通过传递 SQL 语句作为参数, PDO 对象的 prepare() 方法创建了 PDOStatement($stmt);
② :msg_id 前面的冒号表示这是一个占位符(placeholder);
③ 在实际查询前,会用真正的值来替换占位符
④ execute() 方法执行查询
⑤ 必须为 SQL 中的每一个占位符传入值,需要创建一个与占位符数量相同的元素组成的数组,每个占位符都有一个与之匹配的数组元素,数组元素的键名和占位符一致,数组元素的实际值替换占位符
占位符的另外一种形式:
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$sql = 'select * from message where id = ? and flag = ?'; $stmt = $db_conn->prepare($sql);//执行预处理 $stmt->execute(array(2, 1)); $res = $stmt->fetchAll(PDO::FETCH_ASSOC);var_dump($res);
返回:
array0 => array'id' => string '2' (length=1)'content' => string 'world' (length=5)'flag' => string '1' (length=1)
说明:
占位符可以不需要名字,而用 ? 为变量保留一个位置作为没有命名的占位符。
当使用预处理时,为占位符传入的值已经溢出(删除了不需要的字符),因为 MySQL 知道这些都是可能改变的值。
绑定值和预处理语句的变量
当使用 不同的值 重复调用 相同的查询 时,只会有很小的系统弄个开销,可以设置一些元素用于每次查询 - PDOStatement::buildValue():
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$sql = 'select * from message where id = :msg_id and flag = :msg_flag'; $stmt = $db_conn->prepare($sql);//绑定值 $stmt->bindValue(':msg_id', 1);$stmt->bindValue(':msg_flag', 1); $stmt->execute(); $res = $stmt->fetch(PDO::FETCH_ASSOC);$stmt->bindValue('msg_id', 2); $stmt->execute(); $res2 = $stmt->fetch(PDO::FETCH_ASSOC);var_dump($res); var_dump($res2);
输出:
array'id' => string '1' (length=1)'content' => string 'hello' (length=5)'flag' => string '1' (length=1) array'id' => string '2' (length=1)'content' => string 'world' (length=5)'flag' => string '1' (length=1)
还可以使用 PDOStatement::bindParam() 将参数和变量绑定:
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$sql = 'select * from message where id = :msg_id and flag = :msg_flag'; $stmt = $db_conn->prepare($sql);//绑定值 $stmt->bindParam(':msg_id', $msgid);$stmt->bindValue(':msg_flag', 1); $msgid = 1; $stmt->execute(); $res = $stmt->fetch(PDO::FETCH_ASSOC);$stmt->bindValue('msg_id', 2); $stmt->execute(); $res2 = $stmt->fetch(PDO::FETCH_ASSOC);var_dump($res); var_dump($res2);
输出:
array'id' => string '1' (length=1)'content' => string 'hello' (length=5)'flag' => string '1' (length=1) array'id' => string '2' (length=1)'content' => string 'world' (length=5)'flag' => string '1' (length=1)
插入一行数据并获取 ID
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$sql = 'insert into message (content, flag) values (:content, :flag)'; $stmt = $db_conn->prepare($sql);$stmt->execute(array(':content'=>'诸葛四郎和魔鬼党,到底谁抢到那支宝剑',':flag'=>2) );echo 'new id: ',$db_conn->lastInsertId();
输出:new id: 3
说明:lastinsertId() 是 PDO 对象而不是 PDOStatement 对象。
注意:插入中文时为避免乱码,需要在实例化 PDO 对象时增加一个参数 $opt:
$dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = ''; $opt = array(PDO::MYSQL_ATTR_INIT_COMMAND => "set names utf8");try {$db_conn = new PDO($dsn, $username, $pwd, $opt); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }
返回插入、更新或删除的数据的数量
当执行 Insert、Update、Delete 语句时,可以通过 rowCount() 方法 找出多少行内容已经改变:
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$sql = 'update message set flag = :flag where flag = 1'; $stmt = $db_conn->prepare($sql);$stmt->execute(array(':flag'=>3));echo $stmt->rowCount(),' rows uodated.';
输出:2 rows uodated.
说明:rowCount() 方法是 PDOStatement 对象。
删除数据
<?php $dsn = 'mysql:host=localhost;dbname=msg'; $username = 'root'; $pwd = '';try {$db_conn = new PDO($dsn, $username, $pwd); }catch (PDOException $e) {echo 'Could not connect to database.<br />'.$e->getMessage(); }$sql = 'delete from message where id = :msgid'; $stmt = $db_conn->prepare($sql);$stmt->execute(array(':msgid'=>2));echo $stmt->rowCount(),' row(s) deleted.';
输出:1 row(s) deleted.
附:《PDO 学习与使用 ( 一 ) :PDO 对象、exec 方法、query 方法与防 SQL 注入》
PDO 学习与使用 ( 二 ) PDO 数据提取 和 预处理语句相关推荐
- Python爬虫学习之第七天---数据提取-lxml模块和Xpath使用
爬虫学习之第七天-数据提取-lxml模块和Xpath使用 知识点:了解 lxml模块和xpath语法的关系了解 lxml模块的使用场景了解 lxml模块的安装了解 谷歌浏览器xpath helper插 ...
- OpenCV学习笔记(十二)——图像分割与提取
在图像处理的过程中,经常需要从图像中将前景对象作为目标图像分割或者提取出来.例如,在视频监控中,观测到的是固定背景下的视频内容,而我们对背景本身并无兴趣,感兴趣的是背景中出现的车辆.行人或者其他对象. ...
- Servelt学习笔记之二——使用Servlet提取表单中的数据
1.Servlet表单数据 在很多的情况下,我们需要在浏览器,Web服务器和后台程序之间传递数据.浏览器使用两种方法可将这些信息传递到Web服务器,分别为Get方法和Post方法. 1.1.Get方法 ...
- Python爬虫入门(二)数据提取(lxml)
XPath语法和lXml模块 什么是XPath? Xpath是一门在xml和html文档中查找信息的语言,可用来在xml和html文档中对元素和属性进行遍历 Xpath开发工具 chrome插件xpa ...
- 计算机组成原理学习笔记(二)数据的表示和运算(学习王道)
书接上回,让我们开始继续学习第二章节的知识:这里,我们先放一放硬件的知识,来学一下有关数据的知识.虽然本蒟蒻见识比较少,但是还是感觉这一章节的内容实际上是与计算机网络的编码部分的内容有相似之处,我学起 ...
- Kotlin 学习笔记(二)—— 数据类、密闭类、循环写法以及常用集合操作符
在上篇笔记中,我们对 Kotlin 的基本类型.关键字.类与对象,以及与 Java 之间互调的内容有了一些认识,这篇笔记来看看 Kotlin 中几种特殊的类,以及集合相关的常用操作. 1. Kotli ...
- CiteSpace学习笔记(二)——数据的获取(科技文献检索)
科技文本数据的采集是分析的基础,当前数据的采集主要是借助科技文献数据库,并采用成熟的文献检索策略进行. 对于科技文本数据而言,索引型数据库通常收录了除正文以外的所有文献信息,而且还增加了数据库本身对论 ...
- C Primer Plus学习笔记(二)- 数据和C
从一个简单的程序开始 #include <stdio.h>int main(void) {float weight;float value;printf("Please ente ...
- python网络爬虫系列(五)——数据提取 jsonpath模块
一.数据提取概述 知识点 了解 响应内容的分类 了解 xml和html的区别 1. 响应内容的分类 在发送请求获取响应之后,可能存在多种不同类型的响应内容:而且很多时候,我们只需要响应内容中的一部分数 ...
- php pdo输出数据库,PHP中PDO对像及PDOStatement::fetch()的用法数据库查询,结果输出处理...
//isset()判读用户是否提交查询请求 if(isset($_GET['dosubmit'])){ //创建PDO数据库查询对象 $pdo=new PDO('mysql:host=localhos ...
最新文章
- 10、同步机制遵循的原则_我要遵循的10条原则
- 困恼的mappedBy
- List集合与List的子类
- 深度探秘 Java 8 函数式编程(下)
- 山东省能源产业项目动态及未来投资决策建议报告2021版
- XEIM 帮助文档【草稿版】
- 2021-0316:梦中明白在作梦
- wsdl2java参数_wsdl2java参数解释
- 倪捷:智能语音扩展数字化服务
- C语言程序设计实验报告——实验六
- 贪心算法 Y 美味酸奶
- 人脸检测进阶:使用 dlib、OpenCV 和 Python 检测眼睛、鼻子、嘴唇和下巴等面部五官
- html页面如何设置背景,html怎么设置背景
- 向梦想出发 - 全向轮移动底盘搭建
- 负数二进制转换十进制
- 测试还是国外的香?走进海外测试开发工程师
- 京东数据分析工具,同行商家数据快速查看对比
- 阿里云域名实名认证状态查询
- 付宇泽20190905-1 每周例行报告
- 李文卓:揭秘美丽说数据体系建设三部曲
热门文章
- 浅谈文件捆绑技术及实现方式
- 为什么苹果允许用户安装未受信任的企业级开发者所开发的软件?
- 数据库常用日期统计查询
- 韵达快递投诉一直显示服务器繁忙,快递查询自动识别查询方法(6)
- 【学习记录——unity 3D】Stealth秘密行动游戏制作(一)
- appcan注册功能php,appcan是什么
- objectbox No value passed for parameter ‘order‘
- linux4 系统下载,SysLinux 4.0.4 下载
- springboot整合author2
- 软件测试缺陷报告总结