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'];
}
}
Just pass
$DBHas a parameter to any function that needs it:Rather than the
globalkeyword, 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.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.
config.php
Then pass
$configto function calls