[英]Why do we use fetch() while using PDO::query()?
So, we know that PDO::query()
returns PDOStatement object
and the PDOStatement
class implements Traversable
so it allows us to loop through it's object using foreach
loop: 因此,我们知道
PDO::query()
返回PDOStatement object
,并且PDOStatement
类实现了Traversable
因此它允许我们使用foreach
循环遍历其对象:
$db = new PDO($dsn, $dbusername, dbpassword);
$sql = 'SELECT name, surname, gender FROM students';
$stmt = $db->query($sql);
foreach($stmt as $row){
echo $row['name'] . "<br>";
echo $row['surname'] . "<br>";
echo $row['gender'] . "<br>";
}
The code is nice and clean. 该代码是干净的。 (I know that due to the security issues using
query()
can create and we all should be faithful to prepare()
and excecute()
for that.) (我知道,由于存在安全问题,可以使用
query()
来创建,我们都应该忠实地为此prepare()
和excecute()
。)
My question is why do we bother to use fetch()
to retrieve data when we can get the same result without using it. 我的问题是,为什么在不使用数据获取相同结果的情况下,为什么还要使用
fetch()
来检索数据呢? It seems to me an extra step. 在我看来,这是一个额外的步骤。
fetch()
remains most familiar and straightforward method. fetch()
仍然是最熟悉和直接的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.