Example 1°:
$stmt = 'SELECT * FROM table ORDER BY id DESC LIMIT 2';
$Dp = $conn->query($stmt)->fetchAll();
Example 2°:
$stmt = 'SELECT * FROM table ORDER BY id DESC LIMIT 2';
$Dp = $conn->query($stmt);
What's the difference between both examples? I'm new on PDO, and i could not see the difference between both examples.
It kinda depends on what you want to do with the result.
The actual data structures you get from either are very different, but you are probably asking the question because with both you can loop through the result with foreach
.
But fetchAll()
returns a pure PHP array, where as query
returns a PHP object with hidden internals. One of the two you can (for example) call json_encode on.
Generally directly looping over the PDOStatement might be a little faster, because you're not creating a (potentially large) intermediate array.