0

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.

Susi
  • 153
  • 1
  • 3
  • 11
  • `var_dump($Dp);` and you'll see the difference – tkausl Sep 13 '18 at 18:52
  • Example 1 returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch, or FALSE on failure. – PrathapG Sep 13 '18 at 18:55
  • @PrathapG What would be the purpose of placing `fetchAll()` on this code? – Susi Sep 13 '18 at 19:03

1 Answers1

1

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.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • I should asked it in a different away, to clarify my question. I actually want to know if i should put the `fetchAll()` on my code, because as i can see... there's none diffecence when displaying the results on the webpage. – Susi Sep 13 '18 at 19:01
  • @Susi if there is in your case no visible difference, you might get slight performance benefits by not using fetchAll().*however* from a strict architecture design perspective I am not sure if I want my model layer to 'leak' PDOStatement objects. Neither is *wrong* so do what you're the most comfortable with. Architecturally I would prefer return plain PHP arrays because there's going to be some cases in your application you need to post-process the result of the MySQL query, and if you return arrays from the start you can stay 100% consistent. – Evert Sep 13 '18 at 19:20
  • `'leak' PDOStatement objects` I'm not sure if i understood this part right. You mean if i don't use `fetchAll()` i could have some security problems? – Susi Sep 13 '18 at 19:26
  • No I meant 'leak' in terms of 'leaky abstractions'. Your Model-layer should 'abstract' database access. No security issue here. – Evert Sep 13 '18 at 20:50