Why can't I have hyphens in my db_query() I am trying to SELECT all the rows in my MySQL where a field matches a variable using the db_query() function. The variable is not a user input, it is retrieved from another database table based on the user currently logged on, so basically the variable is safe, but it does contain hyphens. Obviously without the hyphens the queries won't work properly, but for some reason if I include the variable the database query  stops working.

When I say it stops working, I can use the functions in the object that is returned but whenever I try to get individual fields I get an error. In case it affects any suggestions, the query has two more 'comparisons' but without the third, containing hyphens, the query could return more than one row. I only want either one or zero rows to be returned.

Anybody any ideas?

UPDATE: The code I have looks something like this:

global $user;

        $ukey = "A-B-C";

        $result = db_query("SELECT NAME FROM ukeys WHERE uid = :uid AND EMAIL = :email AND GENERATEDKEY = :key", array(
            ':uid' =&gt; $user-&gt;uid,
            ':email' =&gt; $user-&gt;mail,
            ':key' =&gt; $ukey 
        ));

        if($result-&gt;rowCount() == 1){
            $name = $result-&gt;NAME;


And the error comes on the bottom line where I try to get the NAME from the results.
Make sure you use proper placeholders in your db queries, as per the Drupal API.

E.g in D7: 

$query = db_query("SELECT * from {foo} WHERE bar = :bar", array(':bar' =&gt; $bar));


or

$query = db_select('foo', 'f')
  -&gt;fields('f')
  -&gt;condition('bar', $bar, '=')
  -&gt;execute();


More info:


Database API
db_query
db_select


UPDATE: Now the the original SQL has been posted, the problem appears to be


Lack of use of fetchObject, fetchAssoc etc.. on the database result


You should be able to use

if($result-&gt;rowCount() == 1){
  $name = $result-&gt;fetchObject()-&gt;NAME;
}


As an aside, better to limit the query if you only want one record returned, e.g

$name = db_select('ukeys', 'u')
  -&gt;fields('u', array('NAME'))
  -&gt;condition('uid', $user-&gt;uid)
  -&gt;condition('EMAIL', $user-&gt;mail)
  -&gt;condition('GENERATEDKEY', $ukey)
  -&gt;range(0,1)
  -&gt;execute()-&gt;fetchfield();


That will return the $name value only, or FALSE if no record exists.