使用查询方法将insert函数转换为预准备语句

时间:2013-03-14 21:46:02

标签: php sql

我有以下代码执行标准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);
}

1 个答案:

答案 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);

}