Fetching only first row from database

by jepster   Last Updated November 14, 2017 18:07 PM

I work with

$mandator = $this->database->select('Mandators', 'm') ->fields('m') ->condition('idMandators', $mandatorId) ->execute() ->fetchAll();

to retrieve my data from database. The result is an array with 1 array item. How can I retrieve always only 1 object, without the array? Like e.g. "->fetchOne".

Tags : 8 database


Answers 2


As per my understanding I would say try to count the number of rows like this $number_of_rows = db_select('node')->countQuery()->execute()->fetchField(); then iterate to get the first count

or // Get a single record out of the database. $node = db_query("SELECT * FROM {node} WHERE nid = :nid", array(':nid' => $nid))->fetchObject();

vbhatia9
vbhatia9
November 14, 2017 17:33 PM

You can simply write (example get node) :)

$result = db_query('SELECT n.nid, n.title, n.created FROM {node} n)->fetchObject();

If you want to get a single value you can use fetchField()

Example (get node title):

$node_title = db_query('SELECT title FROM {node} WHERE nid = :nid', 
array(':nid' => $nid))->fetchField();
Radouane Achebak
Radouane Achebak
November 14, 2017 17:40 PM

Related Questions


Drupal store into own database

Updated July 03, 2015 18:03 PM


Connect to Intersystems Cache DB via ODBC

Updated May 01, 2015 21:03 PM


drupal site is really slow on VPS server

Updated April 03, 2015 21:20 PM