使用预准备语句和php创建一个执行标准DELETE的函数

时间:2013-03-15 14:39:23

标签: php sql prepared-statement

我目前正在通过nettuts.com教程构建一个twitter克隆,并且他们有一个从数据库中删除行的功能,他们正在使用查询方法,但我尝试将该函数转换为准备好的语句。但是我得到Invalid parameter number: parameter was not defined错误。这是函数的代码

public function delete($table, $arr){
    $query = "DELETE FROM " . $table;
    $pref = "WHERE ";

    foreach ($arr as $key => $value) {
        $query .= $pref. $key . " = " . ":" . $key;
        $pref = "AND ";
    }
    $query .= ";";
    $result = $this->db->prepare($query);
    $result->execute($arr);
}

$connect = new Model();

$connect->delete("ribbits", array("user_id" => 2,
                                "ribbit" => "trial ribbit"
                                ));

有人可以告诉我我做错了吗?谢谢!

1 个答案:

答案 0 :(得分:0)

当您将数组传递给->execute()时,键需要在它们之前加上:字符(就像它们出现在SQL查询中一样)。

因此,在delete函数中,构建如下的SQL查询:

public function delete($table, $arr){
    $keys = array();
    $values = array();

    foreach($arr as $key => $value){
        $keys[] = $key . " = :" . $key;
        $values[":".$key] = $value;
    }

    $query = "DELETE FROM " . $table . " WHERE " . implode(" AND ", $keys);
    $result = $this->db->prepare($query);
    $result->execute($values);
}