我有一个搜索表单,可以通过一些自定义值从数据库中获取一些信息。 例如,我的表单包含搜索关键字,类别ID和价格
search keyword
:text category id
:int price
:int 现在,当进行查询以从数据库获取某些数据时,不允许包含search keyword
等字符的值,但仅允许数字category id
,price
模板页面HTML
<form action="<?= base_url() ?>classifieds/search/result/" method="get">
<input type="text" name="search_keyword" id="search_keyword" />
<span id="price_fromto">
<input type="text" name="price_from" id="price_from" />
<input type="text" name="price_to" id="price_to" />
</span>
<select name="currency" id="currency">
<option value="">currency</option>
<option value=""></option>
</select>
<select name="service" id="service">
<option value="">Offer type</option>
<option value="wanted"></option>
<option value="sale">for sale</option>
</select>
<input type="submit" name="sbmtSearch" id="sbmtSearch" value="search" />
</form>
控制器代码
$this - > load - > model('classifieds'); // load model
$q_s = array(
'name' = > $this -> input -> get('search_keyword', true),
'category_id' = > $this -> input -> get('search_category', true),
'type' = > $this - > input -> get('type', true),
'price >' = > $this -> input -> get('price_from', true),
'price <' = > $this -> input -> get('price_to', true), );
// configartion
$output['query'] = $this->classifieds->get_serach_classifieds($q_s); // get content in this model
}
$data['content'] = $this -> load -> view('category', $output, true); // append model content in content variable
$data['title'] = 'search result'; // model model name the page title
$this -> load -> view('index', $data); // load master page ( Container )
分类广告模型
function get_serach_classifieds($q_s) {
$this->db->where('state', 1);
foreach ($q_s as $key => $val) {
if ($val != "" && $val != 0) {
$this->db->where($key, $val);
}
}
return $this->db->get('content');
}
创建的查询(错误)
SELECT * FROM (`content`) WHERE `state` = 1 AND `category_id` = '4' AND `price` > '100' AND `price` < '800' LIMIT 15
假设查询是这样的(正确的)
SELECT * FROM (`content`) WHERE `state` = 1 AND 'name' = 'bmw' AND 'type' = 'wanted' AND `category_id` = '4' AND `price` > '100' AND `price` < '800' LIMIT 15
我的代码中有什么问题导致查询不接受文本值?
答案 0 :(得分:1)
$val != 0
似乎是个问题。与字符串比较时,它不正确。
这样的事情应该有效:
foreach ($q_s as $key => $val) {
if ((is_string($val) && $val != "") || (is_int($val) && $val !=0)) {
$this->db->where($key, $val);
}
}