开发者

Dynamically creating WHERE statements

The snippet below print out a query that fetches users from a DB who's DOB are in a certain age range. In this case, users that are either between 11 and 12 or 17 and 18 years old. I'm trying to dynamically create this query in CodeIgniter Active Record syntax.

This snippet

$age_count = 0;
foreach( $range as $r )
{
    $start_date = strtotime($r[0] . "years ago");
    $stop_date = strtotime($r[1] . "years ago");

    $range = array('dob <' => $start_date, 'dob >' => $stop_date);
    ( $age_count =开发者_如何学JAVA= "0" || $age_count%1 ) ? $this->db->where($range) : $this->db->or_where($range);

    $age_count++;
}
$users = $this->db->get("users")->result_array();

produces this query

SELECT * FROM (`users`) WHERE `dob` < 956351611 AND `dob` > 924729211 OR `dob` < 766962811 OR `dob` > 735426811

The last OR should of course be AND. How can I achieve this? It comes down to knowing when to use or_where() or simply where(). I thought every odd pass through the foreach should be an OR but I'm not quite there yet.

This function might just receive one range (11-12) or several ones.


With the database API, you can use multiple where() to get a WHERE … AND ….

$this->db->where('name', $name);
$this->db->where('title', $title);
$this->db->where('status', $status); 

// WHERE name = 'Joe' AND title = 'boss' AND status = 'active'

(tied from the documentation)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜