سؤال

I am trying to create a simple user registration class using these section of code below. Database file is required in the user.php class and also instantiated just before using the prepared() method. But I still get an undefined method db::prepare() on this line $stmt = $db->prepare ("INSERT INTO users (name, email) VALUES (:name, :email)");

Where am I going wrong ?

database class

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);
                }
    }

User Class

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');
هل كانت مفيدة؟

المحلول

You should access dbh property from your $db object to get a database handler in your User class:

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

Or you can change database class __constructor :

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

And conn() method :

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);
            }
 }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top