带有参数化列名称的准备好的语句不起作用[重复]

问题描述 投票:0回答:1

我在项目中使用准备好的语句时遇到问题。我创建了一个名为 DB 的类,在这个类中我有一个名为“where”的函数,但在这种形式下它不起作用:

public function where($table_name, $key, $value) {
    try {
        $stmt = $this->connection->prepare("SELECT * FROM $table_name WHERE :key = :value ORDER BY id DESC");
        $stmt->execute(array(":key" => $key, ":value" => $value));
        return ($stmt->rowCount() > 0) ? $stmt : false; 
    } catch(Exception $e) {
        return false;
    }
}

但是当我将函数更改为仅使用一个占位符时,它就可以工作了!为什么会出现这种情况?

public function where($table_name, $key, $value) {
    try {
        $stmt = $this->connection->prepare("SELECT * FROM $table_name WHERE $key = :value ORDER BY id DESC");
        $stmt->execute(array(":value" => $value));
        return ($stmt->rowCount() > 0) ? $stmt : false; 
    } catch(Exception $e) {
        return false;
    }
}
php prepared-statement
1个回答
1
投票

准备好的语句中不能有字段。但是,您可以使用

PDO::quote
:

插入它
$stmt = $this->connection->prepare("SELECT * FROM $table_name WHERE " . $this->connection->quote($key) . " = :value ORDER BY id DESC");
© www.soinside.com 2019 - 2024. All rights reserved.