PDO code and PHP undefined error

I have this code to connect to the database

class dbConn{ public $dbname='database'; private $dbhost='localhost'; private $dbusername='username'; private $dbpassword='password'; protected static $db; private function __construct() { try { self::$db = new PDO('mysql:host='.$dbhost.';dbname='.$dbname, $dbusername, $dbpassword ); self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo "Connection Error: " . $e->getMessage(); } } public static function getConnection() { if (!self::$db) { new dbConn(); } return self::$db; } } class Mysql{ function showTables(){ $db = dbConn::getConnection(); $query=$db->query("show tables"); $fetchArray = $query->fetchAll(PDO::FETCH_ASSOC); foreach($fetchArray as $index=>$val) { echo $val; } } } $obj=new Mysql; $obj->showTables(); 

The problem I am facing is that I directly use the database login data in the pdo statement as follows:

 self::$db = new PDO( 'mysql:host=localhost;dbname=databasename', 'root', 'pass'); 

I do not have any problems. But if I use, as indicated above, I take the variables and store the values ​​in them.

 Notice: Undefined variable: dbhost Notice: Undefined variable: dbname Notice: Undefined variable: dbusername Notice: Undefined variable: dbpassword 

The following error comes. Also in another class, it also cannot connect to the database.

Can someone tell me what the problem is?

+4
source share
2 answers

You need to use $this when accessing class properties - $this is the current object.

Example:

 try { self::$db = new PDO('mysql:host='.$this->dbhost.';dbname='.$this->dbname, $this->dbusername, $this->dbpassword ); self::$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo "Connection Error: " . $e->getMessage(); } 

When you call $dbhost , you are looking for a variable in the current scope, in this case, the constructor. $dbhost and $this->dbhost are two different things in this case.

+3
source

Try switching to

 self::$db = new PDO('mysql:host='.$this->dbhost.';dbname='.$this->dbname, $dbusername, $this->dbpassword ); 
+2
source

Source: https://habr.com/ru/post/1469306/


All Articles