Drupal - "OR" condition in db_select()

That's not correct, the default is AND. To use or, you need to use:

$or = db_or();
$or->condition();
$or->condition();
$query->condition($or);

But the main conditions on the query are definitely joined with AND.


You can use this For making OR between 2 conditions ByDefault it is AND

$query=db_select('users','u')->fields('u',array('uid','title','created','uid'));
$query->join('flag_content','fc' , 'u.uid = fc.content_id');

$db_or = db_or();
$db_or->condition('fc.fid', '5' , '=');
$db_or->condition('fc.uid', $uid , '=');
$query->condition($db_or);

$result = $query->execute()->fetchAll();

It is possible to have AND condition within OR suppose you have 3 conditions and if you want it to be like con1 AND con2 OR con3 and evene many other cases in this case you can use db_and like db_or because when you are trying to use db_or all the conditions within db_or takes now in case you want and between those you can use db_and that is little tedious but its possible to implement it heres the example below

 $query = db_select('work_details_table','wd');
$query->join('work_table','w','wd.request_id = w.request_id');
$query->fields('w',array('client_id'));
$query->fields('wd');
$query->condition('wd.request_id',$request_id);
if($status == 5 || $status == 6 || $status == 7){
  $query->condition('wd.status',$status);
}elseif($user_type == 'writer'){
  $query->condition('wd.writer_id',$user_id);  
  $db_or = db_or();
  $db_and = db_and();
    $db_and->condition('wd.status',2);
    $db_and->isNull('wd.editor_id');
  $db_or->condition('wd.status',4);
  $db_or->condition('wd.status',1);
  $db_or->condition($db_and);
  $query->condition($db_or);
}else if($user_type == 'editor'){
  $query->condition('wd.editor_id',$user_id);
  $db_or = db_or();
  $db_and = db_and();
    $db_and->condition('wd.status',2);
    $db_and->isNotNull('wd.editor_id');
  $db_or->condition('wd.status',3);
  $db_or->condition($db_and);
  $query->condition($db_or); 
}
//-----------------------------------------------------------------------------------------
$completed_sku = $query->execute()->fetchAll();

This will give you an idea how the complex and or condition can be handled in Drupal PDO queries .


According to drupal 7 Database documentation the default is AND condition, but if you want to use OR condition then use this;

$db_or = db_or();
$db_or->condition('n.type', 'event', '=');
$db_or->condition('n.type', 'article', '=');
$query->condition($db_or);

Tags:

Database

7