我正在尝试解决我的数据库类在准备时遇到的错误。错误存在于这个函数中,但我似乎可以找到一种正确的方法来修复它。也许我只是忽略了一些简单的事情。任何帮助表示赞赏。
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();