Fatal error: Call to a member function prepare() on a non-object

I keep getting

Fatal error: Call to a member function prepare() on a non-object in /var/www/auto/functions.php on line 72

for the following but i have checked all post variables all are being passed.

Can any one spot my error?!


function add_device ($devicename,$devicebrand,$deviceremoteid,$devicechannel) {
GLOBAL $dbh;
$insertdev= $dbh->prepare("INSERT INTO `devices` (`name`, `brand`, `remoteid`, `channel`) VALUES (:name, :brand, :remote, :channel)");
$insertdev->bindParam(':name', $devicename);
$insertdev->bindParam(':brand', $devicebrand);
$insertdev->bindParam(':remote', $deviceremoteid);
$insertdev->bindParam(':channel', $devicechannel);
$insertdev->execute();
echo "<br><b>Device Added to Database</b><br />";
}

Without my getting into a discussion on using “global”, does it “work” if you declare the global outside of the function?

nope


Notice: Undefined variable: dbh in /var/www/auto/functions.php on line 72

Fatal error: Call to a member function prepare() on a non-object in /var/www/auto/functions.php on line 72

Where is $dbh coming from? Maybe the problem is there?

$dbh is declared in an include config.php file.

funny thing is the other functions work spot on just how i’ve done the above it appears to be only this one function that is throwing a wobbler

this is my functions script

https://raw.github.com/txt3rob/RPI-Control/master/functions.php

very weird i have resolved it by doing an include inside the function of the config file although it’s already declared at the top and global has been set!

If you resolved it by including a config file the global variable is apparently defined inside the config file. Just by declaring it as global will not work if the global variable does not even exist in the very first place, thats why you have to include/import it from a config file or whatever file it was initially defined. Do not confuse global variables with superglobals, the latter is available everywhere in your script but a global variable has to be defined first.

On the other hand, I recommend against using global variable in the very first place. Its an extremely bad programming practice no matter whether you use procedural, functional or OO programming paradigm, a habit you need to get rid of before its too late. Instead, you can use dependency injection by passing the $dbh object to the very function/method you are calling.