0
votes

When i try to get the returned value of a function in another class i get Undefined Variable. $dbh is null

at my entry point file i instantiate a DB_Functions object:

require_once ('/DB_Functions.php');
$db = new DB_Functions();

this is on DB_Function.php file.

   class DB_Functions {
        private $db;
        public $dbh;

        //put your code here
        // constructor
        function __construct() {
            require_once 'DB_Connect.php';
            // connecting to database
            $this->db = new DB_Connect();
            $this->dbh = $this->db->connect();
        }
    }

then i use the db object like that:

    if ($db->isUserExisted($username)) {}....

The error is inside isUserExisted(...) function. Line 89 is $statement = $dbh....:

  public function isUserExisted($username) {
        $statement = $dbh->prepare("SELECT username FROM users WHERE username = :username");
        $statement->bindParam(':username', $username);
}

This is in DB_Connect.php file that instantiates the PDO object and returns it

public function connect() {
        require_once('config.php');
        $dbh = new PDO('mysql:host=' . hostname . ';dbname=' . db_name, username, password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        echo 'Connected to database';
        return $dbh;
}

Error is:

Notice: Undefined variable: dbh in D:\xampp\htdocs\pharm_project\DB_Functions.php on line 89

Line 89 is:

$statement = $dbh->prepare("SELECT username FROM users WHERE username = :username");

1
I'm assuming the first file is pharm_project\DB_Functions? Where is line 89? Sorry for all the question, crystal ball is broken. - castis
in line 89 i try to use the PDO object - Manos
So DB_Functions.php:89 is $dbh = new PDO('mysql:host=' . hostname . ';dbname=' . db_name, username, password);? - castis
this is line 89----> $statement = $dbh->prepare("SELECT username FROM users WHERE username = :username"); - Manos
Why would you not include that super useful information in your question? You need to put in that, and all the code around it... - castis

1 Answers

1
votes

Your problem is here

public function isUserExisted($username) {
    $statement = $dbh->prepare("SELECT username FROM users WHERE username = :username");
    $statement->bindParam(':username', $username);
}

$dbh does not exist inside the scope of this function. You will either need to pass in the database connection as an argument (as in isUserExisted($dbh, $username)) or store it in the object you're calling that function on.

For example, in that objects __construct(), you might do $this->dbh = $dbh or something. Then your function would change to

public function isUserExisted($username) {
    $statement = $this->dbh->prepare("SELECT username FROM users WHERE username = :username");
    $statement->bindParam(':username', $username);
}

More information can be found here