Suppose i’m querying my database with a simple SELECT statement.
$sql='SELECT * FROM products';
$s=$db->prepare($sql);
$s->execute();
foreach($s as $v){
echo $v['productName'];
}
$s->closeCursor();
However i saw the following code, using fetchAll() to do the same:
$sql='SELECT * FROM products';
$s=$db->prepare($sql);
$s->execute();
$products=$s->fetchAll();
$s->closeCursor();
foreach($products as $v){
echo $products['productName'];
}
First of all, I know that fetchAll() shouldn’t be used for large result sets.
However, the question is: If we can directly transverse the PDOStatement object returned by the prepare() method why do we they make fetchAll() (and fetch())available?
It seems that the only advantage will be free the connection earlier!
The answer is simple:
Because you have to separate business logic from presentations logic.
Means first you have to get all the required data and only then start the output.
And fetchAll become quite handy in this matter.
Well, after closer look at your question
I think that such a “direct traversing” is merely a syntax sugar, having good old fetch() underneath or something like that.