Drupal 7 : Select Query Format


Dynamic queries refer to queries that are built dynamically by Drupal rather than provided as an explicit query string. All Insert, Update, Delete, and Merge queries must be dynamic. Select queries may be either static or dynamic. Therefore, “dynamic query” generally refers to a dynamic Select query.

All dynamically built queries are constructed using a query object, requested from the appropriate connection object. As with static queries, in the vast majority of cases the procedural wrapper may be used to request the object. Subsequent directives to the query, however, take the form of methods invoked on the query object.


$result = db_select('table_name', 'table_alias')
    ->fields('table_alias') // just pass table_alias if you need select all the fields Or ->fields('table_alias',array('field_1', 'field_2', 'field_3', 'field_4', 'field_5'))
    ->condition('field_1', $field_1,'=')
    ->condition('field_2', $field_1,'=')
    ->execute()
    ->fetchAssoc();

this will work as good as we using simple select query as below;

$result = "SELECT * FROM table_name as alias WHERE field_1 = "'.$field_1.'" AND field_2 = "'.$field_2.'" ";


execute(): function will execute the query directly;

fetchAssoc(): function will fetch Associate array of records set directly;

Thanks.