I’m getting the following message:
Notice: Undefined variable: dbh in /var/www/PDO/Functions/PDOFunctions.php on line 12 Fatal error: Call to a member function prepare() on a non-object in /var/www/PDO/Functions/PDOFunctions.php on line 12
$dbh = new PDO('mysql:host=localhost;dbname=pdo', 'root', 'xxxxxxxxxxx');
global $dbh;
function PDOFetch($Var)
{
$sth = $dbh->prepare("$Var"); //Error Line
$sth->execute();
$result = $sth->fetchAll();
return $result;
}
function PDONumb ($Var)
{
$Query = $dbh->prepare("{$Var}");
$Execute->execute();
$count = $Execute->rowCount();
return $count;
}
What is the problem with my code?
In PHP, to access a global variable in a function, you have to declare that it belongs to global scope by using the global keyword.
All variables used in a function are local to that function unless declared to be imported from the global scope.
The NOTICE error is a helpful warning that you may be doing something you didn’t expect.