想法格式化查询字符串

Aut*_*cus 1 php mysql cakephp-1.3

我正在尝试创建一个查询字符串

$sql = 'select * from table where '. $option1. $option2 etc
Run Code Online (Sandbox Code Playgroud)

我该怎么做呢.每个查询都有不同数量的选项.上面有2个,但可能多达10个

谢谢

rid*_*rid 5

例如,您可以将这些保存在数组中.就像是:

$options = array('option1', 'option2', 'etc');
$sql = 'SELECT * FROM table WHERE ' . implode(' AND ', $options);
Run Code Online (Sandbox Code Playgroud)

您甚至可以使用数组编写整个查询,具体取决于您需要更改的内容(我的意思是,只使您需要更改的内容可配置).例如:

$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);
Run Code Online (Sandbox Code Playgroud)