PDOStatement 包含什么以及 fetch/fetchAll 的用途是什么? [英] What does a PDOStatement contain and what is the use of fetch/fetchAll?
问题描述
我无法理解 1) PDOStatement 对象内部是什么以及 2) 为什么我需要 fetch() 或 fetchAll() 方法.
I cannot understand 1) what is inside a PDOStatement object and 2) why I would need a fetch() or fetchAll() method.
我的数据库:一个名为animals"的简单表,包含 3 列(id、名称、物种).
My database: One simple table called 'animals' with 3 columns (id, name, species).
我的代码:
try {
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
exit( $e->getMessage() );
}
try {
$sql = "SELECT * FROM animals";
$results = $pdo->query($sql);
print_r($results);
} catch (PDOException $e) {
echo $e->getMessage();
}
首先,print_r(或var_dump)打印:PDOStatement Object ( [queryString] => SELECT * FROM animal )
First off, print_r (or var_dump) prints this: PDOStatement Object ( [queryString] => SELECT * FROM animals )
但是如果我这样写:
foreach($results as $row) {
echo $row['id'] . ' ' . $row['name'] . ' ' . $row['species'];
}
我的表格的每个内容都被打印出来.
every content of my table is printed.
所以 1) 如果我的对象中存在该信息,为什么 print_r 不显示任何信息?
So 1) why print_r doesn't show anything of that info if it exists inside my object?
和
2) 为什么我需要 $results->fetch()
或 $results->fetchAll()
来获取我已经从数据库并在结果集 $results 中?
2) why I would need $results->fetch()
or $results->fetchAll()
to fetch the info I have already fetched from the database and are in the result set $results?
推荐答案
因为 API 就是这样设计的,并且考虑到了灵活性.
Because that's how the API is designed, with flexibility in mind.
您的对象不包含所有数据集.相反,PDOStatement
实现了 迭代器
/可遍历
接口,为每个 foreach
操作隐式调用 ->fetch
.
Your object does not contain all datasets. Instead PDOStatement
implements the Iterator
/Traversable
interface, implicitly calling ->fetch
for each foreach
operation.
然而,有些人更喜欢手动使用 ->fetch
或 ->fetchAll
一次提取所有行.
Some people however prefer to use ->fetch
manually, or ->fetchAll
for pulling all rows at once.
这篇关于PDOStatement 包含什么以及 fetch/fetchAll 的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!