db_class.php
<?php
class db_mysql
{
private $dbhost;
private $dbusername;
private $dbpassword;
private $db;
//Class is called with all parameters to make a successful connection.
//
function __construct($dbhost,$dbusername,$dbpassword,$db)
{
global $dbh;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$db", $dbusername, $dbpassword);
foreach($dbh->query('show tables;') as $row) {
print_r($row);
}
//$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
//Function to execute a query in the database and return result in a array
//
function db_mysql_query($queryst)
{
foreach($dbh->query($queryst) as $row) {
print_r($row);
}
}
}
index.php:
<?php
include 'db_class.php';
$db_m = new db_mysql('localhost','root','','arsaas');
$db_m->db_mysql_query('show tables;');
?>
Executing index.php gives the following error: Notice: Undefined variable: dbh in C:\xampp\htdocs\srry\db_class.php on line 32
Fatal error: Call to a member function query() on a non-object in C:\xampp\htdocs\srry\db_class.php on line 32
Why does it say dbh is undefined variable when it is instantiated and declared as a global variable in the class constructor?
Any help is appreciated. Thanks in advance.
AR