Custom tables and their queries

Sometimes we need to put data in a custom table in drupal. Usually when this happens we also need to do some fancy queries on these tables.
The db_select function is usually the starting point here, and with methods like join() and condition() and fields() we are able to fetch most of the data.
 

The other day I needed to get data that was between certain dates. Here is what I did:
 

$snippet = 'NOW() BETWEEN `start_datum` AND DATE_ADD(`start_datum`, INTERVAL `aantal_weken` WEEK) AND `weekopdracht_id` >0';
    $return = array();

    $res = db_select('pos4_target', 't')
    ->fields('t', array('target_id'))
    ->fields('t', array('naam'));
    if($condition == true){
        $res->where($snippet);
    }
    $result = $res->execute()->fetchAllKeyed();


    foreach($result as $row => $value){
        $return[$row] = $value;
    }

    return $return;

So we also have a where() method. It accepts query string as the first variable and an array of variables for when the querystring has any arguments in it.

Add new comment