Reputation: 87
I am making a transfer from using mysql query lines to PDO for a current project and i have an issue. For this task i am not allowed to use any classes (stupid restriction if you ask me)
Basically i was getting a non object error because my main php file could not see the set variable $DBH. I solved this problem by setting each function with a $DBH global; so it could be used, however ive been told this is bad coding practice. Is this the case? and if so how can i make my function see my config variable.
Config.php
try
{
$DBH = new PDO("mysql:host=host;dbname=db", "username", "Password");
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
echo $e->getMessage();
}
a php file
function concName($concID)
{
global $DBH; //THIS is the area that im told is bad practice - can this be eliminated?
$stmt = $DBH->prepare("SELECT CONCAT(`Firstname`, ' ', `Surname`) AS 'Membername' FROM `members` WHERE `MemberID`= :MemberID");
$stmt->bindValue(":MemberID",$concID);
$stmt->execute();
while($row = $stmt->fetch())
{
return $row['Membername'];
}
}
Upvotes: 4
Views: 1992
Reputation: 270677
Just pass $DBH
as a parameter to any function that needs it:
function concName($concID, $DBH)
{
$stmt = $DBH->prepare("SELECT CONCAT(`Firstname`, ' ', `Surname`) AS 'Membername' FROM `members` WHERE `MemberID`= :MemberID");
$stmt->bindValue(":MemberID",$concID);
$stmt->execute();
while($row = $stmt->fetch())
{
return $row['Membername'];
}
}
Rather than the global
keyword, you can also access it from the $GLOBALS[]
array, which is more explicit about the variable's origins when used in the function. Passing a parameter is still preferable to this though.
function concName($concID)
{
// Better than `global` keyword, use `$GLOBALS['DBH']` every time you access it in outside global scope
// Still not preferred to passing a parameter though.
$stmt = $GLOBALS['DBH']->prepare("SELECT CONCAT(`Firstname`, ' ', `Surname`) AS 'Membername' FROM `members` WHERE `MemberID`= :MemberID");
$stmt->bindValue(":MemberID",$concID);
$stmt->execute();
while($row = $stmt->fetch())
{
return $row['Membername'];
}
}
If you have multiple globals defined in your configuration file, you can wrap them all in an array which you pass into functions needing them. That wraps them tidily into a package of config options made available to any function that needs them.
// Global array of config options
$config = array();
// various options
$config['option1'] = 'option 1';
$config['option2'] = 12345;
try
{
$config['DBH'] = new PDO("mysql:host=host;dbname=db", "username", "Password");
$config['DBH']->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e){
echo $e->getMessage();
}
Then pass $config
to function calls
Upvotes: 3