我正在尝试创建一个查询字符串
$sql = 'select * from table where '. $option1. $option2 etc
我将如何做到这一点。每个查询都有不同数量的选项。上面有2个,但可能多达10个
感谢
答案 0 :(得分:5)
例如,您可以将这些保存在数组中。类似的东西:
$options = array('option1', 'option2', 'etc');
$sql = 'SELECT * FROM table WHERE ' . implode(' AND ', $options);
您甚至可以使用数组编写整个查询,具体取决于您需要更改的内容(我的意思是,只需将您需要更改的内容配置为可配置)。例如:
$query = array(
'select' => 'SELECT *',
'from' => 'FROM table',
'where' => 'WHERE',
'conditions' => array('a = 2', '(b = 3) OR (c = 4)'));
/* ... */
if ($something_happens_that_needs_to_change_the_table) {
$query['from'] = 'FROM another_table';
}
/* ... other things that need to change the query somehow ... */
$query['conditions'] = implode(' AND ', $query['conditions']);
$query_to_count = $query;
$query_to_count['select'] = 'SELECT COUNT(*) AS total';
$query_to_count = implode(' ', $query_to_count);
$query = implode(' ', $query);
答案 1 :(得分:0)
如果您正在使用Cake,请创建一系列条件并将其提供给paginate
$conditions['Model.field1'] = somevalue;
$conditions['Model.field2 LIKE'] = '%what_ever%';
...... etc
$conditions['Model.field3'] = 36;
$search_result = $this->paginate('Model', $conditions);