(编辑:jimmy 日期: 2025/7/6 浏览:2)
PDOStatement::fetchAll
PDOStatement::fetchAll — 返回一个包含结果集中所有行的数组(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
说明
语法
array PDOStatement::fetchAll ([ int $fetch_style [, mixed $fetch_argument [, array $ctor_args = array() ]]] )
参数
fetch_style
fetch_argument
根据 fetch_style 参数的值,此参数有不同的意义:
ctor_args
当 fetch_style 参数为 PDO::FETCH_CLASS 时,自定义类的构造函数的参数。
返回值
PDOStatement::fetchAll()
返回一个包含结果集中所有剩余行的数组。此数组的每一行要么是一个列值的数组,要么是属性对应每个列名的一个对象。
使用此方法获取大结果集将导致系统负担加重且可能占用大量网络资源。与其取回所有数据后用PHP来操作,倒不如考虑使用数据库服务来处理结果集。例如,在取回数据并通过PHP处理前,在SQL 中使用 WHERE 和 ORDER BY 子句来限定结果。
实例
获取结果集中所有剩余的行
<"SELECT name, colour FROM fruit"); $sth->execute(); /* 获取结果集中所有剩余的行 */ print("Fetch all of the remaining rows in the result set:\n"); $result = $sth->fetchAll(); print_r($result); "htmlcode">Fetch all of the remaining rows in the result set: Array ( [0] => Array ( [NAME] => pear [0] => pear [COLOUR] => green [1] => green ) [1] => Array ( [NAME] => watermelon [0] => watermelon [COLOUR] => pink [1] => pink ) )获取结果集中单独一列的所有值
下面例子演示了如何从一个结果集中返回单独一列所有的值,尽管 SQL 语句自身可能返回每行多列。
<"SELECT name, colour FROM fruit"); $sth->execute(); /* 获取第一列所有值 */ $result = $sth->fetchAll(PDO::FETCH_COLUMN, 0); var_dump($result); "htmlcode">Array(3) ( [0] => string(5) => apple [1] => string(4) => pear [2] => string(10) => watermelon )根据单独的一列把所有值分组
下面例子演示了如何返回一个根据结果集中指定列的值分组的关联数组。该数组包含三个键:返回的 apple 和 pear 数组包含了两种不同的颜色,而返回的 watermelon 数组仅包含一种颜色。
<"INSERT INTO fruit(name, colour) VALUES ("); $insert->execute(array('apple', 'green')); $insert->execute(array('pear', 'yellow')); $sth = $dbh->prepare("SELECT name, colour FROM fruit"); $sth->execute(); /* 根据第一列分组 */ var_dump($sth->fetchAll(PDO::FETCH_COLUMN|PDO::FETCH_GROUP)); "htmlcode">array(3) { ["apple"]=> array(2) { [0]=> string(5) "green" [1]=> string(3) "red" } ["pear"]=> array(2) { [0]=> string(5) "green" [1]=> string(6) "yellow" } ["watermelon"]=> array(1) { [0]=> string(5) "green" } }每行结果实例化一个类
下面列子演示了 PDO::FETCH_CLASS 获取风格的行为。
<"SELECT name, colour FROM fruit"); $sth->execute(); $result = $sth->fetchAll(PDO::FETCH_CLASS, "fruit"); var_dump($result); "htmlcode">array(3) { [0]=> object(fruit)#1 (2) { ["name"]=> string(5) "apple" ["colour"]=> string(5) "green" } [1]=> object(fruit)#2 (2) { ["name"]=> string(4) "pear" ["colour"]=> string(6) "yellow" } [2]=> object(fruit)#3 (2) { ["name"]=> string(10) "watermelon" ["colour"]=> string(4) "pink" } }每行调用一次函数
下面列子演示了 PDO::FETCH_FUNC 获取风格的行为。
<"{$name}: {$colour}"; } $sth = $dbh->prepare("SELECT name, colour FROM fruit"); $sth->execute(); $result = $sth->fetchAll(PDO::FETCH_FUNC, "fruit"); var_dump($result); "htmlcode">array(3) { [0]=> string(12) "apple: green" [1]=> string(12) "pear: yellow" [2]=> string(16) "watermelon: pink" }总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接
在去年的5月23日,借助Intel Bridge Technology以及Intel Celadon两项技术的驱动,Intel为PC用户带来了Android On Windows(AOW)平台,并携手国内软件公司腾讯共同推出了腾讯应用宝电脑版,将Windows与安卓两大生态进行了融合,PC的使用体验随即被带入到了一个全新的阶段。
最新资源