我正在尝试创建一个简单的搜索页面,但我不是100%确定如何编写实际的搜索字符串(如果变量存在,使用适当的AND等)这里是代码:
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.';
};
我尝试过使用(如果键入!= null然后搜索类型=“其中type ='X'”)但是如果搜索需要,我无法弄清楚如何放置AND之前/之后。如果这有道理?
答案 0 :(得分: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.';
};