0

I'd like to know how to properly write mySQL statement using ZEND in this case:

SELECT * FROM `users` WHERE role_id = 2 AND status = 2 AND bddate BETWEEN '1988-05-07' AND '1991-01-01' ORDER BY lastname DESC

I'll have if statements, for ex. if in the filter user selected role_id I'll include it in WHERE and so on, the same with the rest of them.

So far I have 1 WHERE condition and I have done it like this (now I need more complicated one):

    $select = $this->select()
            ->setIntegrityCheck(false)
            ->from(array('u'=>'users'))
            ->join(array('r'=>'user_roles'), 'u.role_id = r.role_id', array('role'=>'title'));          
    if(count($filters) > 0) {
        foreach($filters as $field => $filter) {
            $select->where($field . ' = ?', $filter);
        }
    }

    if(null != $sortField) {

        $select->order($sortField);

    }
2
  • I do not really understand your problem. It seems like you are already able to build a query. So what is more complicated in your first select statement / where exactly are you having problems? Commented Jan 16, 2013 at 10:02
  • I wrote the query, but how to do it for ZEND_DB? in my code I have only 1 WHERE, and in the new statement that I want to implement I have several in addition with BETWEEN Commented Jan 16, 2013 at 10:15

1 Answer 1

3

Okay, so you are having a problem with the BETWEEN. There are two possible solutions for this:

a) You use two where clauses for to split up the BETWEEN, so you get

$select = $this->select()
//... other conditions
    ->where('bddate >= ?', '1988-05-07')
    ->where('bddate <= ?', '1991-01-01');

OR

b)

$select = $this->select()
//... other conditions
    ->where ('bddate BETWEEN '1988-05-07' AND '1991-01-01');

I would recommend option a), because it properly escapes your values.

Sign up to request clarification or add additional context in comments.

2 Comments

so, I can do as many ->where's as I want? (judging according you example)
@Mikey Yes, you can. They all get AND-ed together. You actually already do this in your code... "foreach($filters as $field => $filter) { $select->where($field . ' = ?', $filter); }"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.