Search code examples
phpmysqldrupal-7

db_select when column name is a mysql keyword


Selecting using db_select and when database column happens to be a reserved mysql word (when in this case) results in an error.

Table:

+-----------------------------------+------------+--------+
|               sort_id             |    when    |  user  |
+-----------------------------------+------------+--------+
| 1                                 | 1448270950 |    123 |
| 3                                 | 1448270955 |     12 |
| 50                                | 1448270959 |     45 |
+-----------------------------------+------------+--------+

Standard drupal7 select using db_select:

$query = db_select('naughty_table', 'd')
    ->fields('d', array('sort_id', 'when', 'user'))
    ->condition('user', $uid)
    ->limit($limit)
    ->execute();

Column named when is the problem here.

I know I can write the query using plain SQL:

db_query("SELECT sort_id, user, `when` FROM {naughty_table} WHERE user = :user", array(":user" => $user_id));

But there should be a way to solve this using regular db_select?


Solution

  • where() should be used instead instead:

    $query = db_select('my_table', 'd')
      ->fields('d', array('sort_id', '`when`', 'user'))
      ->condition('user', '123')
      ->where('`when` = :timestamp', array(':timestamp' => 1448160590))
      ->execute();