petek
petek

Reputation: 1088

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.

Upvotes: 3

Views: 3548

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157839

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.

Upvotes: 3

Related Questions