Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

php - PDO Prepared statement Inside a class

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();

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?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
    ));
}

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...