I am using pdo and I have set the connection string in a config file such as
$db = new PDO(\"mysql:host=localhost;dbname=mydbname\", \'root\', \'pass\');
If you declared/instatiated $db
in the global scope (or any scope other than the function/method), and tried to use it in a function/method, it will not work. Read this.
If your PDO object failed to instantiate or was unset before the method call, you may also recieved this error. Try var_dump(is_object($db));
and/or var_dump($db);
to check.
You need to do one of the following:
Instantiate the PDO object within the method (probably not practical or best option):
function foo () {
$db = new PDO( ... );
...
$query = $db->query( ... );
}
Instantiate the PDO object in the global scope and use the global
keyword to import it into the method:
$db = new PDO( ... );
function foo () {
global $db;
$query = $db->query( ... );
}
Instantiate the PDO object in the global scope and use the superglobal $GLOBALS
array to access it.
$db = new PDO( ... );
function foo () {
$query = $GLOBALS['db']->query( ... );
}
Instantiate the PDO object in the global scope and pass it as a parameter to your method.
$db = new PDO( ... );
function foo ($db) {
$query = $db->query( ... );
}
foo($db);
Instantiate the PDO object in the global scope and pass into your object as a property.
$db = new PDO( ... );
class foo {
public $db;
public function bar ($db) {
$query = $this->db->query( ... );
}
}
$foo = new foo;
$foo->db = $db;
$foo->bar($db);