【发布时间】:2011-09-09 15:36:09
【问题描述】:
我正在尝试创建一个查询字符串
$sql = 'select * from table where '. $option1. $option2 etc
我将如何去做。每个查询都有不同数量的选项。上面有2个,但可能多达10个
谢谢
【问题讨论】:
标签: php mysql cakephp-1.3
我正在尝试创建一个查询字符串
$sql = 'select * from table where '. $option1. $option2 etc
我将如何去做。每个查询都有不同数量的选项。上面有2个,但可能多达10个
谢谢
【问题讨论】:
标签: php mysql cakephp-1.3
例如,您可以将它们保存在一个数组中。比如:
$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);
【讨论】:
如果您使用的是 Cake,请创建一个条件数组并将其提供给分页
$conditions['Model.field1'] = somevalue;
$conditions['Model.field2 LIKE'] = '%what_ever%';
...... etc
$conditions['Model.field3'] = 36;
$search_result = $this->paginate('Model', $conditions);
【讨论】: