php pdo fetch作用是从结果集中获取下一行,其语法是“pdostatement::fetch ([ int $fetch_style [, int]...);”,参数“fetch_style”表示控制下一行如何返回给调用者。
php pdo fetch() 详解
环境:(php 5 >= 5.1.0, php 7, pecl pdo >= 0.1.0)
pdostatement::fetch — 从结果集中获取下一行
说明
pdostatement::fetch ([ int $fetch_style [, int $cursor_orientation = pdo::fetch_ori_next [, int $cursor_offset = 0 ]]] ) : mixed
从一个 pdostatement 对象相关的结果集中获取下一行。fetch_style 参数决定 pod 如何返回行。
参数
fetch_style
控制下一行如何返回给调用者。此值必须是 pdo::fetch_* 系列常量中的一个,缺省为 pdo::attr_default_fetch_mode 的值 (默认为 pdo::fetch_both )。
pdo::fetch_assoc:返回一个索引为结果集列名的数组
pdo::fetch_both(默认):返回一个索引为结果集列名和以0开始的列号的数组
pdo::fetch_bound:返回 true ,并分配结果集中的列值给 pdostatement::bindcolumn() 方法绑定的 php 变量。
pdo::fetch_class:返回一个请求类的新实例,映射结果集中的列名到类中对应的属性名。如果 fetch_style 包含 pdo::fetch_classtype(例如:pdo::fetch_class | pdo::fetch_classtype),则类名由第一列的值决定
pdo::fetch_into:更新一个被请求类已存在的实例,映射结果集中的列到类中命名的属性
pdo::fetch_lazy:结合使用 pdo::fetch_both 和 pdo::fetch_obj,创建供用来访问的对象变量名
pdo::fetch_num:返回一个索引为以0开始的结果集列号的数组
pdo::fetch_obj:返回一个属性名对应结果集列名的匿名对象
cursor_orientation
对于 一个 pdostatement 对象表示的可滚动游标,该值决定了哪一行将被返回给调用者。此值必须是 pdo::fetch_ori_* 系列常量中的一个,默认为 pdo::fetch_ori_next。要想让 pdostatement 对象使用可滚动游标,必须在用 pdo::prepare() 预处理sql语句时,设置 pdo::attr_cursor 属性为 pdo::cursor_scroll。
offset
对于一个 cursor_orientation 参数设置为 pdo::fetch_ori_abs 的pdostatement 对象代表的可滚动游标,此值指定结果集中想要获取行的绝对行号。
对于一个 cursor_orientation 参数设置为 pdo::fetch_ori_rel 的pdostatement 对象代表的可滚动游标,此值指定想要获取行相对于调用 pdostatement::fetch() 前游标的位置
返回值
此函数(方法)成功时返回的值依赖于提取类型。在所有情况下,失败都返回 false 。
范例
<?php // 将数据库访问信息设置为常量: header( 'content-type:text/html;charset=utf-8 '); define ('db_user', 'root'); define ('db_password', '*****'); define ('db_host', 'localhost'); define ('db_name', 'ryan'); date_default_timezone_set('prc'); //设置时区 try { $dsn = 'mysql:host='.db_host.';dbname='.db_name.''; $dbc = new pdo($dsn, db_user, db_password); $dbc->exec('set names utf8'); if (!$dbc) { echo "无法连接数据库!"; exit; } $q = "select * from users;"; $res = $dbc->prepare($q);//准备查询语句 $res->execute(); $result = $res->fetch(pdo::fetch_num); echo "返回首行列数" . count($result) . "<br>"; // 在不知道列的情况下,实现循环输出首行内容 for ($i = 0; $i <= count($result)-1; $i++) { echo $result[$i] . " "; } } catch (pdoexception $e) { echo '不能连接 mysql: ' . $e->getmessage(); }
更多相关技术文章,请访问!