0

我目前正在阅读关于构建 twitter 克隆的 nettuts.com 教程,他们有一个用于从数据库中删除行的函数,并且他们正在使用查询方法,但我尝试将该函数转换为准备好的语句。但是我得到了 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"
                                ));

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

4

1 回答 1

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);
}
于 2013-03-15T15:00:53.423 回答