I have created a file name database.php and here is it’s content
<?php
#Start Session
session_start();
#Start Output Buffering
ob_start();
#Set Default TimeZone
date_default_timezone_set('Asia/Kolkata');
#Define Connection Constant
define('HOST','localhost');
define('USERNAME','user');
define('PASSWORD','pass');
define('DATABASE','database');
//Define Configuration Constant
define('DATE', date("d-F-Y/H:ia"));
#Connect to the database
try
{
#Define Connection String Using PDO.
$DBH = new PDO('mysql:host='.HOST.';dbname='.DATABASE,USERNAME,PASSWORD);
#Set Error Mode to ERRMODE_EXCEPTION.
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
//Log Errors into a file
file_put_contents("resources/logs/Connection-log.txt", DATE.PHP_EOL.$e->getMessage().PHP_EOL.PHP_EOL, FILE_APPEND);
}
?>
and now i have defined a PHP’s class and i have declared a method where i want to fetch some values based on the connection above. i have included the database.php file.
here is my code.
include('../../config/database.php');
class Property
{
public function getAllCountries()
{
#Query Using Prepared Statement
$STH = $DBH->query('SELECT * FROM countries');
#Set the Fetch Mode
$STH->setFetchMode(PDO::FETCH_ASSOC);
$countries = array();
while($row = $STH->fetch())
{
$countries[] = $row['name'];
return $countries;
}
}
}
$property = new Property;
echo $property->getAllCountries();
when i initialize the class it doesn’t have any problem but when i try to call $property->getAllCountries(); method it gives me the following error.
Notice: Undefined variable: DBH in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/class.property.php on line 8
Fatal error: Call to a member function query() on a non-object in /Applications/MAMP/htdocs/kokaris/administrator/resources/library/models/class.property.php on line 8
what is wrong with my code?
The problem is that
$DBHis not in scope at the time of the call$DBH->query().$DBHis in the global scope, while the call is within a function’s scope (getAllCountries). Unlike some other languages, global variables are not accessible within functions unless you specifically declare them.The one-line workaround for this is to use the global value of
$DBHwithin the function:However, this is probably a bad idea, because you have now locked yourself in to a particular way of handling database connections. It would be better to pass the database object as a parameter to the constructor, store it in an object variable, and retrieve it when you need to use it.
You would then need to initialise your class with the DB object passed as a parameter: