db类实例化后的undefined方法prepare()错误

时间:2014-05-04 00:01:44

标签: php mysql sql pdo prepare

我正在尝试使用以下代码段创建一个简单的用户注册类。 user.php类中需要数据库文件,并且在使用prepared()方法之前也会实例化。但我仍然在这一行得到一个未定义的方法db :: prepare() $stmt = $db->prepare ("INSERT INTO users (name, email) VALUES (:name, :email)");

我哪里错了?

数据库类

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', 'name@email.com');

1 个答案:

答案 0 :(得分:2)

您应该从dbh对象访问$db属性,以获取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);
            }
 }