我有以下代码执行标准INSERT。我可以重写此函数来执行相同但不使用
$this->db->query($query)
我希望它能够通过使用预准备语句来执行相同操作,因为此代码似乎非常容易受到SQL注入。这就是代码。
private function insert($table, $arr){
$query = "INSERT INTO " . $table . " (";
$pref = "";
foreach ($arr as $key => $value) {
$query .= $pref . $key;
$pref = ", ";
}
$query .= ") VALUES (";
$pref = "";
foreach ($arr as $key => $value) {
$query .= $pref. "'" . $value . "'";
$pref = ", ";
}
$query = .= ");";
return $this->db->query($query);
}
我用PDO连接到mysql。
EDİT:我写了下面的代码,没有问题。
private function insert($table, $arr){
$query = "INSERT INTO " . $table . " (";
$pref = "";
foreach ($arr as $key => $value) {
$query .= $pref . $key;
$pref = ", ";
}
$query .= ") VALUES (";
$pref = "";
foreach ($arr as $key => $value) {
$query .= $pref. ":" . $key ;
$pref = ", ";
}
$query .= ");";
$result = $this->db->prepare($query);
$result->execute($arr);
}
答案 0 :(得分:0)
从http://www.php.net/manual/en/pdo.prepare.php示例#1,尝试类似
的内容private function insert($table, $arr){
$query = "INSERT INTO " . $table . " (";
$pref = "";
foreach ($arr as $key => $value) {
$query .= $pref . $key;
$pref = ", ";
}
$query .= ") VALUES (";
$pref = "";
foreach ($arr as $key => $value) {
$query .= $pref. ":" . $key;
$pref = ", ";
}
$query = .= ")";
$this->db->prepare($query);
$this->db->execute($arr);
}