成员函数prepare()对非对象错误

时间:2013-08-05 00:48:22

标签: php database class

我正在尝试解决我在编写数据库时遇到的错误。错误存在于此函数中,但我似乎找到了一种正确的方法来解决它。也许这只是一件我只是忽略的简单事。任何帮助表示赞赏。

public function query($query){
    $this->stmt = $this->dbh->prepare($query);
    }

和全班:

class Database{
    private $host      = "localhost";
    private $user      = "root";
    private $pass      = "";
    private $dbname    = "pwgame";

    private $dbh;
    private $error;
    private $stmt;

    public function __construct(){
        // Set DSN
        $dsn = 'mysql:host=' . $this->host . ';charset=utf8;dbname=' . $this->dbname;
        // Set options
        $options = array(
            PDO::ATTR_PERSISTENT    => true,
            PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_EMULATE_PREPARES => false
        );
        // Create a new PDO instance
        try{
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        }
        // Catch any errors
        catch(PDOException $e){
            $this->error = $e->getMessage();
        }
    }

    public function query($query){
    $this->stmt = $this->dbh->prepare($query);
    }

    public function execute(){
    return $this->stmt->execute();
    }

    public function resultset(){
    $this->execute();
    return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function single(){
    $this->execute();
    return $this->stmt->fetch(PDO::FETCH_ASSOC);
    }

    public function rowCount(){
    return $this->stmt->rowCount();
    }

    public function lastInsertId(){
    return $this->dbh->lastInsertId();
    }

    public function bind($param, $value, $type = null){
    if (is_null($type)) {
        switch (true) {
            case is_int($value):
                $type = PDO::PARAM_INT;
                break;
            case is_bool($value):
                $type = PDO::PARAM_BOOL;
                break;
            case is_null($value):
                $type = PDO::PARAM_NULL;
                break;
            default:
                $type = PDO::PARAM_STR;
        }
    }
    $this->stmt->bindValue($param, $value, $type);
    }

只是包含试图使用它的页面..

$db->query('INSERT INTO users (username, password, email, email_hash) VALUES (:username, :pass, :email, :email_hash)');
$db->bind(':username', $user);
$db->bind(':pass', $hash);
$db->bind(':email', $email);
$db->bind(':email_hash', $email_hash);
$status = $db->execute();

0 个答案:

没有答案