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?
source share