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

<?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;  ?>

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::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES utf8',
                PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,  //  _SILENT (pub) || _WARNING || _EXCEPTION  (dev)

1 Answer 1


The idea is very bad, for many reasons.

  • your query could fail. It will result in a torn design, with only half the page rendered.
  • sometimes you must display a different text if the query returned no rows
  • sometimes you need to send your data in a different format. For example not as HTML, but as a JSON-formatted array in response to AJAX call.
  • a bowl of spaghetti made from HTML, PHP and SQL makes it hard to maintain. There should be a separation between the data manipulation and the data presentation.

These are my options for the connection:

Some of them are wrong as well

  • a cargo cult persistent connection will do you no good
  • charset should be set in the DSN
  • ERRMODE should NEVER be set to silent. On a live server is should be the same as on dev, i.e. set to EXCEPTION. Errors should be only hidden from a site user, not completely silenced.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.