Is there any reason to not do this?
Putting the query directly inside a foreach-statment when the only time the result is going to be used is within that location..
<select>
<?php foreach($dbh->query('SELECT id, name, so FROM Employees ORDER BY so') as $e): ?>
<option value="<?=$e['so']?>">-- after "<?=$e['name']?>" --</option>
<?php endforeach; ?>
</select>
It seems like I don't have to provide the fetchAll() when doing so either.
In fact, if I just do the following, and not adding any fetch()-methods at all, I still get the result if I put $employees into a foreach-loop:
$employees = $dbh->query('SELECT id, name, so FROM Employees ORDER BY so');
foreach($employees as $e){ /* works same as above */ }
when I do print_r($employees), I only get this string:
PDOStatement Object ( [queryString] => SELECT id, name, so FROM Employees ORDER BY so )
Is that correct behaviour?
These are my options for the connection:
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_EMULATE_PREPARES=>false,
PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES utf8',
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, // _SILENT (pub) || _WARNING || _EXCEPTION (dev)
);
query()call inside theforeachsee this answer. @YourCommonSense kind of explains this in phpdelusions.net \$\endgroup\$