Drupal - How do I get only one result using db_query()

If you wish to fetch only one result you could use fetchField with db_query to fetch the result, e.g.:

$zip_code = db_query("SELECT zip from {zipcodes} WHERE city = :city LIMIT 1", array(":city" => $city))->fetchField();

You could also fetch the values retrieved from the query's returned result source using options like fetchObject() similar to methods of conventional PHP (mysql_fetch_object) coding like using and get results.


Here's how to use the Database API in Drupal 7 without writing a MySQL query:

$query = db_select('zipcodes', 'z')
  ->fields('z', array('zip'))
  ->condition('z.city', $city)
  ->range(0, 1)
  ->execute();
$result = $query->fetchObject();
print $result->zip;

You have to loop your $query, you can't suppose you only have one result with the above given query.

foreach ($query as $row) {
  print $row->zip;
}

If you know you only have one result, you could call fetchObject on your query ->

$query = db_query("select zip from {zipcodes} where city = :city limit 1", array(":city" => $city))->fetchObject();

print $query->zip should then give you what you want.

Tags:

Database

7