我喜欢Dynamic sql的灵活性,我喜欢Prepared Statements的安全性改进性能.所以我真正想要的是动态准备语句,这很麻烦,因为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,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后面封装值来避免代码注入.
有没有人有意见或建议?我需要注意哪些问题?