0

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...

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
EnrageDev
  • 91
  • 6
  • @Softi, what is your question? What is wrong with your code? – Abhay Feb 25 '12 at 07:08
  • @Abhay: Dont think there is any error... i just thought about the background... if there is any possibility for my code to be "inefficient" or anything like this. – EnrageDev Mar 25 '12 at 21:48

1 Answers1

0

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

j_mcnally
  • 6,928
  • 2
  • 31
  • 46