Although this is an old question, I would like to point out an alternate method. The problem is that Drupal chokes on the parameter of the MySQL DATE_FORMAT
function specifying how the date should be formatted. Suppose you have this code:
$SQL = 'SELECT DATE_FORMAT(NOW(), "%e %b %Y")';
$query = $db->query($SQL);
$query->execute();
Executing this in Drupal (as of version 8.8.2) will result in the message "The website encountered an unexpected error. Please try again later." and the following entry in the log:
Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S22]:
Column not found: 1054 Unknown column '%e %b %Y' in 'field list':
SELECT DATE_FORMAT(NOW(), "%e %b %Y"); Array ( )
To work around that, you can use a bound parameter for the date format. This code will work:
$SQL = 'SELECT DATE_FORMAT(NOW(), :dateFormat)';
$terms = [':dateFormat' => '%e %b %Y'];
$query = $db->query($SQL, $terms);
$query->execute($terms);
$result = $query->fetchAll();
I suspect the %
symbols in the DATE_FORMAT
are what's causing the problem. Moving those to a bound parameter solves the issue because Drupal always passes those directly to the database as a literal string.
Hoping this may help some future sufferer.