2009-09-15 30 views
1

我试图创建一个简单的搜索页面,但我不是100%确定如何编写实际的搜索字符串(使用适当和的等如果变量存在)下面的代码:动态创建一个mysql搜索字符串?

if ($post) { 

    //get all search variables 
    $type = JRequest::getVar('type'); 
    $classifications = JRequest::getVar('classifications', array(0), 'post', 'array'); 
    $rating = JRequest::getVar('rating'); 
    $status = JRequest::getVar('status'); 
    $cterms = JRequest::getVar('cterms'); 
    $clientid = JRequest::getVar('clientid'); 
    $company = JRequest::getVar('company'); 
    $address = JRequest::getVar('address'); 
    $name = JRequest::getVar('name'); 
    $surname = JRequest::getVar('surname'); 
    $city = JRequest::getVar('city'); 
    $state = JRequest::getVar('state'); 
    $pcode = JRequest::getVar('pcode'); 
    $country = JRequest::getVar('country'); 

    //create search string 
    echo "SELECT * FROM #__db_clients "; <- the query is supposed to be done here.. it's in as echo because I was trying to spit it out before trying to make it run.. :) 

} else { 

    echo 'There has been an error, please try again.'; 

}; 

我已经尝试使用(如果type!= null,则检索类别=“其中type =‘X’”),但我无法弄清楚如何放置和/后,如果之前它需要的搜索..如果让感?

回答

2

这是一个简单的例子。我不知道JRequest :: getVar返回的是什么样的数据(总是一个字符串或混合类型?),但是这应该让你开始。请确保在foreach循环中使用适用的转义方法:

if ($post) { 
    $criteria = array(); 
    //get all search variables 
    $criteria['type'] = JRequest::getVar('type'); 
    $criteria['classifications'] = JRequest::getVar('classifications', array(0), 'post', 'array'); 
    $criteria['rating'] = JRequest::getVar('rating'); 

    //if there are some criteria, make an array of fieldName=>Value maps 
    if(!empty($criteria)) { 
     $where = array(); 
     foreach($criteria as $k => $v) { 
      //IMPORTANT!! 
      //$v is the value of the field, needs to be quoted correctly!! 
      $where[] = "$k = '$v'"; 
     } 
    } 
    //create search string 
    $query = "SELECT * FROM #__db_clients"; 

    if($where) { 
     $query .= " where " . join(' AND ', $where); 
    } 
} else {  
    echo 'There has been an error, please try again.'; 
}; 
+2

将内容插入到表达式中时,一定要将转义应用于'$ v'。 – 2009-09-15 01:36:53

+1

@ Bill Karwin - 绝对谢谢!我不知道哪个转义方法适用于他的应用程序,所以我在答案中写了一个注释(以及代码注释)。 – karim79 2009-09-15 01:40:32

+0

非常感谢,这肯定会帮助我得到我的代码:)非常感谢! – SoulieBaby 2009-09-15 01:42:31