Info Unfollowers
Info Unfollowers

Reputation: 23

PDO PHP Connection, Fatal Error

My Connection Class;firstcode.php

class DB_functions {
    public $db;
    function __construct() {
        try{
            $db = new PDO("mysql:localhost;dbname=xxx;charset=utf8","xxx","xxx");
            echo 'Connected';
        }catch(PDOException $e){
            print $e->getMessage();
            echo "No Connection";
        }
    }
    function __destruct() {}

    public function test(){
        
        $query = $db->query("SELECT * FROM User", PDO::FETCH_ASSOC);
        if($query->rowCount()){
            foreach ($query as $row) {
                print_r($row);
            }
        }
    }

}

My test PHP File;

 <?php

require_once('firstcode.php');

$db = new db_functions();

$t = $db->test();

?>

And the error I got;

Notice: Undefined variable: db in firstcode.php on line 20

Fatal error: Call to a member function query() on a non-object in firstcode.php on line 20

Thanks in Advance

Upvotes: 2

Views: 1956

Answers (1)

Darren
Darren

Reputation: 13128

You're almost there. In your class, you need to change each iteration of $db with:

$this->db

So your class would look like this:

class DB_functions {
    public $db;
    function __construct() {
        try{
            $this->db = new PDO("mysql:localhost;dbname=xxx;charset=utf8","xxx","xxx");
            echo 'Connected';
        }catch(PDOException $e){
            print $e->getMessage();
            echo "No Connection";
        }
    }
    function __destruct() {}

    public function test(){

        $query = $this->db->query("SELECT * FROM User", PDO::FETCH_ASSOC);
        if($query->rowCount()){
            foreach ($query as $row) {
                print_r($row);
            }
        }
    }

}

As you're referencing the internal class variable. It's only accessible within the class scope and is referenced through $this.

Upvotes: 3

Related Questions