Database query with WHERE and ORDER BY Can't figure out why the following query executes directly through phpMyAdmin perfectly well:

SELECT id FROM `stats` WHERE type="load" ORDER BY id DESC LIMIT 1


but firing this:

db_query('SELECT id FROM {stats} WHERE type = '.$param.' ORDER BY id DESC LIMIT 1')-&gt;fetchField();


from a module outputs:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'load' in 'where clause': SELECT id FROM {server_stats} WHERE type = load5 ORDER BY id DESC LIMIT 1; Array ( ) in server_tab_stats_submit() (line 750 of /home/dev/public_html/sites/all/modules/custom/server/server.inc).


Column's name there is "type", I don't know why Drupal query thinks "load" is a column, it is just a value derived from $param variable.
Try This

$nid = db_query('SELECT id FROM {stats} WHERE type = :type ORDER BY id DESC LIMIT 1', array(':type' =&gt; $param))-&gt;fetchField();


Refer db_query for more information...