我喜欢动态SQL的灵活性,也喜欢预处理语句的安全性和性能改进。因此,我真正想要的是动态预处理语句,但由于bind_param和bind_result接受“固定”的参数数量,所以这很麻烦。因此,我利用eval()语句来解决这个问题。但我觉得这是个坏主意。以下是我想表达的示例代码:
// array of WHERE conditions
$param = array('customer_id'=>1, 'qty'=>'2');
$stmt = $mysqli->stmt_init();
$types = ''; $bindParam = array(); $where = ''; $count = 0;
// build the dynamic sql and param bind conditions
foreach($param as $key=>$val)
{
$types .= 'i';
$bindParam[] = '$p'.$count.'=$param["'.$key.'"]';
$where .= "$key = ? AND ";
$count++;
}
// prepare the query -- SELECT * FROM t1 WHERE customer_id = ? AND qty = ?
$sql = "SELECT * FROM t1 WHERE ".substr($where, 0, strlen($where)-4);
$stmt->prepare($sql);
// assemble the bind_param command
$command = '$stmt->bind_param($types, '.implode(', ', $bindParam).');';
// evaluate the command -- $stmt->bind_param($types,$p0=$param["customer_id"],$p1=$param["qty"]);
eval($command);
那最后的eval()语句是一个坏主意吗?我试图通过将值封装在变量名$param之后来避免代码注入。
是否有人有意见或其他建议?我需要注意哪些问题吗?