-1
我正在嘗試使用以下代碼的這些部分創建一個簡單的用戶註冊類。 數據庫文件在user.php類中是必需的,並且在使用prepared()方法之前也要實例化。但我仍然在這一行上得到一個未定義的方法db :: prepare() $stmt = $db->prepare ("INSERT INTO users (name, email) VALUES (:name, :email)");
未定義方法db class被實例化後的prepare()錯誤
我在哪裏出錯了?
數據庫類
require_once('tryerrors.php');
class db {
private $dsn = 'mysql:host=127.0.0.1;dbname=users';
private $username = 'root';
private $password = '';
public $dbh;
public function __construct(){
$this->conn();
}
public function conn(){
try {
$this->dbh = new PDO($this->dsn, $this->username, $this->password);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
$error = new Errors();
echo $error->displayError($e);
}
}
用戶類別
require_once ('db.php');
class Users{
public $dbh;
public function reg_user($name, $email) {
try{
$db = new db;
$stmt = $db->prepare ("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->execute(array($name, $email));
} catch (PDOException $e) {
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
}
}
$reg = new Users;
$reg->reg_user('name', '[email protected]');