Search code examples
phppdofetchall

PHP PDO fetchAll() vs direct foreach loop


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.


Solution

  • 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.