格式化查询字符串的想法

问题描述

| 我正在尝试查询字符串
$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);
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...