选择使用db_select
,当数据库列恰好是一个保留的mysql字(本例中为when
)时,将导致错误。
+-----------------------------------+------------+--------+
| sort_id | when | user |
+-----------------------------------+------------+--------+
| 1 | 1448270950 | 123 |
| 3 | 1448270955 | 12 |
| 50 | 1448270959 | 45 |
+-----------------------------------+------------+--------+
标准drupal7 select using db_select
:
$query = db_select('naughty_table', 'd')
->fields('d', array('sort_id', 'when', 'user'))
->condition('user', $uid)
->limit($limit)
->execute();
标题为when
的列是这里的问题。
我知道我可以使用普通SQL编写查询:
db_query("SELECT sort_id, user, `when` FROM {naughty_table} WHERE user = :user", array(":user" => $user_id));
但是应该是一种使用常规db_select解决这个问题的方法吗?
where()
应改为
$query = db_select('my_table', 'd')
->fields('d', array('sort_id', '`when`', 'user'))
->condition('user', '123')
->where('`when` = :timestamp', array(':timestamp' => 1448160590))
->execute();
你的查询应该是这样的:
$query = db_select('naughty_table', 'd')
->fields('d', array('`sort_id`', '`when`', '`user`'));
->condition('`user`', $uid)
->limit($limit)
->execute();
注意字段周围的反引号。事实上,phpMyAdmin总是使用这些反号来避免遇到保留字问题。
话虽如此,在表中避免将字段命名为保留字总是一个好主意(我知道您没有创建它,但只是一个注释)。