我有一个搜索表单,可以通过一些自定义值从数据库中获取一些信息。 例如,我的表单包含搜索关键字、类别 ID 和价格
搜索关键字
: text类别 id
: int价格
: 整数
现在,当查询从数据库中获取某些数据时,不允许包含 search keyword
等字符的值,但只允许包含 category id
等数字, 价格
。
模板页面 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>
Controller 代码
$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
我的代码中有什么问题导致查询不接受文本值?
最佳答案
$val != 0
似乎是问题所在。与字符串相比,情况并非如此。
像这样的东西应该可以工作:
foreach ($q_s as $key => $val) {
if ((is_string($val) && $val != "") || (is_int($val) && $val !=0)) {
$this->db->where($key, $val);
}
}
关于php - 不接受数据库查询中的文本值,但只允许数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22707443/