Muhammad Saqib
Muhammad Saqib

Reputation: 121

Build a Search Query in zend Framework

i am using ZendFrameWork 1.11.5 i need to make a Multi form search queries like i have 5 fields like

name (text box)
city (dropDown)
zipCode (text box)
type (dropdown)

now the problem is ... in text Box user can enter anything it could be correct info or not.. kindly suggest me how to build a fast query.what kind of options i have.. also i tried this but not working.. not giving me correct result..

Select * from table where type =       '%$pType%'
                OR  sex     LIKE     '%$sex%'
                OR  race    LIKE      '%$race%'
                OR  kind    LIKE     '%$kind%'
                OR  country LIKE      '%$Country%'
                OR  state   LIKE     '%$statesIDs%'
                OR  zipcode LIKE     '%$zip%'";

Upvotes: 2

Views: 2090

Answers (1)

hungneox
hungneox

Reputation: 9829

Here is my sample code for you. Your code should depends on your needs, query may joins with another table, or instead of LIKE you can use MATCH...AGAINST for more accuracy result. This code depends on each parameter that user enter for making a final query.

//In DbTable
public function search($params)
{
    $query = $this->select()
                   ->from(
                    array('tbl'=>'table'),
                    array('name','city','zipcode','type')
                    );
    $query = $this->_makeParams($query,$params);
    return $this->fetchAll($query);
}

private function _makeParams($query, $params)
{
    $name = isset($params['name']) ? trim($params['name']) : '';
    $city = isset($params['city']) ? trim($params['city']) : '';
    $zipcode = isset($params['zipcode']) ? trim($params['zipcode']) : '';
    $type = isset($params['type']) ? trim($params['type']) : '';

    if($name!='')
    {
        $name = '%'.$this->quote($name).'%';//quote is my own function
        $query->where("tbl.name LIKE '?'",$name); 
    }

    if($city!='')
    {
        $query->where("tbl.city=?",$city);
    }

    if($zipcode!='')
    {
        $query->where("tbl.zipcode=?",$zipcode);
    }

    if($type!='')
    {
        $query->where("tbl.type=?",$type);
    }

    return $query;

}

Upvotes: 5

Related Questions