mister martin
mister martin

Reputation: 6252

How to pass DB connection to another class?

I'm currently trying to pass a DB connection as follows:

class Test {
    public $user;
    public $db;

    function __construct() {
        // connect to database
        try {
            $this->db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_DATABASE.'', DB_USERNAME, DB_PASSWORD);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $err) {
            die($err->getMessage());
        }
        $this->user = new User($this->db);
    }
}

class User {
    public $db;

    function __construct($db) {
        $this->db = $db;
    }

    // execute some query
    $sql = "SELECT * FROM test";
    $sth = $this->db->prepare($sql);
    $sth->execute();
    $result = $sth->fetch();
    if(!empty($result)) {
        echo '<pre>';
        var_dump($result);
        echo '</pre>';
    }
}

But I get: Fatal error: Call to a member function prepare() on a non-object. What am I doing wrong?

Upvotes: 1

Views: 1148

Answers (1)

Bill Karwin
Bill Karwin

Reputation: 562250

You've got the passing-db-to-class-constructor part correct.

But this is not a valid class definition the way you've coded it. You need to put those lines of code (following // execute some query) into a function. Lines of code can't live where they are, floating around inside the User class but not inside a function. It's not legal PHP.

You should also check for error status after each call to prepare() or execute(). They return FALSE if there's an error, like an SQL syntax error, or the table doesn't exist, etc.

class User {
    public $db;

    function __construct($db) {
        if (! $db instanceof PDO) { die("What are you trying to pull anyway?"); }
        $this->db = $db;
    }

    function doSomething() {
        // execute some query
        $sql = "SELECT * FROM test";
        $sth = $this->db->prepare($sql);
        if ($sth === false) {
            die(print_r($this->db->errorInfo(), true));
        }
        $status = $sth->execute();
        if ($status === false) {
            die(print_r($sth->errorInfo(), true));
        }
        $result = $sth->fetch();
        if(!empty($result)) {
            echo '<pre>';
            var_dump($result);
            echo '</pre>';
        }
    }
}

Upvotes: 1

Related Questions