简体   繁体   English

为什么在使用PDO :: query()时使用fetch()?

[英]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. 在我看来,这是一个额外的步骤。

  1. Because there are queries that return only one row, for which a foreach loop would be an extra step . 因为有些查询仅返回一行,所以foreach循环将是一个额外的步骤
  2. Because traversable PDOStatement is just a syntax sugar, just another way to do it , for anyone who like it this way. 因为可遍历的PDOStatement只是语法糖, 所以对于喜欢这种方式的任何人来说,这都是另一种实现方式。 While fetch() remains most familiar and straightforward method. 虽然fetch()仍然是最熟悉和直接的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM