开发者

idea to format a query string

I am trying to make a query string

$sql = 'select * from table where '. $option1. $option2 etc

how would I go about making that. every query开发者_高级运维 will have different number of options. above have 2, but it could be as many as 10

thanks


You could hold these in an array for example. Something like:

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

You could even compose the whole query with an array, depending on the things you need to change (what I mean is, only make the things you need to change configurable). For example:

$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);


If you're using Cake, make an array of conditions and feed it to paginate

$conditions['Model.field1'] = somevalue;
$conditions['Model.field2 LIKE'] = '%what_ever%';
...... etc
$conditions['Model.field3'] = 36;


$search_result = $this->paginate('Model', $conditions);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜