PDO准备好的语句在类中 [英] PDO Prepared statement Inside a class

查看:78
本文介绍了PDO准备好的语句在类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的数据库类中使用一种更新方法,使我能够更新一条记录.我试图确保我可以在不必重复编写同一条语句的另一个实例中使用该方法.这是我的代码:

I am trying to use an update method inside my Database class where I could be able to update a record. I am trying to make sure that I could use the method in another instance where i dont have to repeat writing the same statement. Here is my code:

<?php 
require 'init.php';
class Database {
    private $conn;

    public function __construct() {
        try {
            $this->conn = new PDO('mysql:host=localhost;dbname=school', DB_USER, DB_PASS);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            return false;
        }
    }

    public function update($table, $key, $value, $id) {
        $stmt = $this->conn->prepare("UPDATE $table SET $key = $value WHERE id = :id");
        return $stmt->execute(array($key => $value, 'id' => $id));
    }
}
$database = new Database();

我的问题是,当我尝试实例化类$result = $database->update('admin', 'username', 'golobo', 13);时遇到一些错误 问题是我在做什么错了?

My problem is i get some errors when i try to instantiate the class $result = $database->update('admin', 'username', 'golobo', 13); the question is what am I doing wrong?

谢谢

推荐答案

您不太正确地使用PDO的绑定功能.您应该执行以下操作:

You aren't using the bindings feature of PDO quite right. You should do something like the following:

public function update($table, $key, $value, $id) {
    $stmt = $this->conn->prepare(
        "UPDATE $table SET $key = :value WHERE id = :id"
    );
    return $stmt->execute(array(
        ':value' => $value,
        ':id' => $id
    ));
}

首先,您需要将要绑定的整个字符串放入绑定数组的键中.因此,您放置':id'而不是'id'.同样,在$table$value的情况下,您将变量直接放入查询中,但随后试图将它们彼此绑定,这没有任何意义.

First, you need to put the entire string to be bound into the key of the binding array. So you put ':id' rather than 'id'. Also you were putting the variables directly into the query in the case of $table and $value, but then attempting to bind them to each other, which doesn't make sense.

不能使用PDO绑定表和列名称.

tables and column names can't be bound using PDO.

这篇关于PDO准备好的语句在类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆