我正在尝试创建一个从post接收用户输入数组的函数,并动态生成查询语句并绑定params。到目前为止,我能够使用引用列表创建查询语句,但是遇到了绑定参数的问题,因为我需要编写一大块switch开关来使其工作。我正在使用CodeIgniter。
/* user input array sample
array ("title" => "abc",
"year" => ["start"=>1999, "end"=>2010]
)
*/
class Listing extends CI_model {
private ref_list = [
'title' => 'title LIKE :title',
'year' => "(year BETWEEN :start AND :end)"
]
private clause_list = [] // to be generated
private param_list = [] // to be generated
function query_create ( array $post_input ) {
foreach ($post_input as $post_key => $post_value ) {
// for clause list
foreach ($this->ref_list as $ref_key => $ref_value ){
if ($post_key == $ref_key ) {
$this->clause_list[] = $ref_value;
}
}
// for param list
switch($post_key) {
case "title":
$value = $post_value;
$this->param_list[] = [":title", "%{$value}%", PDO::PARAM_STR];
break;
case "year":
$start = $post_value['start'];
$value = $post_value['end'];
$this->param_list[] = [":start", "%{$start}%", PDO::PARAM_INT];
$this->param_list[] = [":end", "%{$end}%", PDO::PARAM_INT];
break;
}
}
/* loop through clause list array to create query statement */
$select_string = "SELECT * FROM song ";
$clause_string = "WHERE ".implode ("AND", $this->clause_list);
$query_stmt = $select_string . $clause_string
/* bind param in PDO */
if (is_array($this->param_list) && !empty($this->param_list)){
foreach ($this->param_list as $index) {
$bind = $index[0];
$value = &$index[1];
$param = $index[2];
$query->bindParam ($bind, $value, $param);
}
}
}
}
正如您所看到的,当发布更多输入时,切换块会变得很大,我有什么方法可以缩短它?