问题描述
|
我正在尝试查询字符串
$sql = \'select * from table where \'. $option1. $option2 etc
我将如何去做。每个查询将具有不同数量的选项。上面有2个,但可能多达10个
谢谢
解决方法
例如,您可以将它们放在一个数组中。就像是:
$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);