Php 动态创建mysql搜索字符串?
我正在尝试创建一个简单的搜索页面,但我不能100%确定如何使用适当的AND等来编写实际的搜索字符串如果变量存在,代码如下:Php 动态创建mysql搜索字符串?,php,mysql,search,Php,Mysql,Search,我正在尝试创建一个简单的搜索页面,但我不能100%确定如何使用适当的AND等来编写实际的搜索字符串如果变量存在,代码如下: if ($post) { //get all search variables $type = JRequest::getVar('type'); $classifications = JRequest::getVar('classifications', array(0), 'post', 'array'); $rating = JReq
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.';
};
我尝试过使用if type!=null then searchtype=where type='X',但如果搜索需要,我无法确定如何放置前/后。。这有意义吗 这是一个简单的例子。我不知道什么样的数据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.';
};
在表达式中插入$v时,一定要将转义应用于它。@Bill Karwin-谢谢,绝对感谢!我不知道哪种转义方法适用于他的应用程序,所以我在答案和代码注释中都添加了注释。非常感谢,这肯定会帮助我运行代码:非常感谢@SoulieBaby-np,确保彻底测试你将其转化为什么,它有助于在每个步骤中放置大量诊断回音语句,以便你可以看到发生了什么。并确保所有内容都正确转义/引用。祝你好运嗯,它不喜欢foreach$条件,因为$k=$v{我得到这个错误:解析错误:语法错误,意外的'=',期望