phpmysqlsearchsqlbuilder

php, mysql search entry function


i want to build a search fnction for my php class which builds a sql search string for searching specific entries with a short line of code:

$obj -> search(array('key'=>'value'),true_or_false);

i wonder if there is any easier possibility to get the self results... in fact i have to build this function with operational sign to get the possibility for AND or "OR" depencies...

if you use this,

$obj->search(array('key'=>'value','+2ndkey'=>'2ndvalue'))

it generates the sql query string with "AND" instead of "OR"

any suggestions?

i'm looking especially for a simple and clean solution to make "LIKE" or "=" dynamic and use a simple 1-liner to get my results... :)

/*
*/
function search($params,$strict = false)
{
    if(!is_array($params)||!count($params))
        return false;

    $sql = 'SELECT `sampleid` FROM `sampletable` WHERE ';
    $n = 0;
    foreach ( $params AS $key => $value )
    {
        $key = mysql_real_escape_string($key);
        $op = substr($key,0,1)=='+'?true:false;
        $key = $op ? substr($key,1,strlen($key)):$key;
        $value = mysql_real_escape_string($value);
        $str = sprintf($strict!==false?"`%s` = '%s'":"`%s` LIKE '%%%s%%'",$key,$value);

        if($n!=0)
        {
            $sql .= $op ? ' AND ' : ' OR ';
        }
        $sql .= $str;
        $n++;
    }

    $sql .= ' LIMIT 25'; //implode($strict!==false?' AND ':' OR ',$req) . ' LIMIT 25';
    return $this -> db -> get($sql);
}

sry for my english, it's not my native language...


Solution

  • If you return instead an instance of you object you can chain and build the query in a private string and then your last statement could be compile/run the statement.

    $db->select('*')->from('table')->where('a = 1')->compile();

    returns

    select * from table where a = 1