How does PHP PDO :: query really execute?

A bit of confusion about what PDO :: query does. Fully understand the difference between it and preparation and execution, but it is unclear whether the query requests a sample. According to PHP.net:

PDO :: query - executes an SQL statement, returning the result set as a PDOStatement object

which is confirmed by:

$s = $pdo->query('SELECT * FROM user');
var_dump($s);

which outputs:

object(PDOStatement)#2 (1) {
  ["queryString"]=> string(18) "SELECT * FROM user"
}

So it explicitly gives us a PDOStatement object, ready to run fetch or fetchAll. HOWEVER. Take the following code taken from the PHP.net manual:

$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
    print $row['name'] . "\t";
    print $row['color'] . "\t";
    print $row['calories'] . "\n";
}

This means that executing PDO :: query actually fetch inside and return the result (which is mentioned in the initial description of the method). However, if this is the case, then a subsequent call to fetch should return the second line, however it is not, you will still get the first line.

fetch reset , ? , ? ? - ? , PDOStatement? , __set_state __debugInfo

+4
1

, PHP PDO::query. PDOStatement. , Traversable, . , fetch().

,

PDO:: query . PDOStatement . .

foreach ($conn->query($sql) as $row)

$stmt = $conn->query($sql);
foreach ($stmt as $row)

foreach , ,

PDOStatement?

.

, .

+4

Source: https://habr.com/ru/post/1663253/


All Articles