3

Is there any difference between these two:

$stmt = $db->prepare('SELECT * FROM ARTICLES');
$stmt->execute();

foreach ($stmt as $article) {
    echo $article['title'];
}

and

$stmt = $db->prepare('SELECT * FROM ARTICLES');
$stmt->execute();

$articles = $stmt->fetchAll();
foreach ($articles as $article) {
    echo $article['title'];
}

Is there any major differences between those two methods?

EDIT: I'm just asking, because both appear to work the same for me.

petek
  • 953
  • 4
  • 14
  • 24

1 Answers1

3

The only difference is that the former doesn't consume extra memory for the returned records like the latter does.

However, given you generally shouldn't fetch more records than could be shown on a single HTML page anyway, the difference considered to be a negligible one.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • Thank you so much. And thank you for that link. A lot of useful information there I can learn from :) EDIT: Will mark as answer in 7 min. ^^ – petek Feb 08 '17 at 15:13
  • Thank you whoever upvoted this answer, but I would rather prefer this upvote to go for the question instead. – Your Common Sense Feb 08 '17 at 15:33
  • So is while loop the best to itterate over results? Or does it not matter that much which one of the 3 I use? – petek Feb 08 '17 at 16:07
  • while loop with fetch is similar to foreach. so I'd rather say it doesn't matter which one to use. – Your Common Sense Feb 08 '17 at 16:08