2014-05-04 41 views
-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]'); 

回答

2

您應該從$db對象訪問dbh財產在你User類來獲得一個數據庫處理程序:

$db = new db; 
$stmt = $db->dbh->prepare ("INSERT INTO users (name, email) VALUES (:name, :email)"); 

或者你可以更改database__constructor

public function __construct(){ 
    return $this->conn(); 
} 

而且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); 
     return $this->dbh; 
     } catch (PDOException $e) { 
      $error = new Errors(); 
      echo $error->displayError($e); 
      } 
}