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\');
I recommend to use a good pattern called Registry. And a simple implementation in PHP:
abstract class Registry {
private static $_tools = array();
public static function set($name, $value) {
self::$_tools[$name] = $value;
}
public static function get($name) {
return (isset(self::$_tools[$name]) ? self::$_tools[$name] : null);
}
}
Usage:
$db = new PDO("mysql:host=localhost;dbname=mydbname", 'root', 'pass');
Registry::set('db', $db);
//In some other part of code
$query = Registry::get('db')->query("select aUsername,aPassword,aOnline,aLastlogin from tbl_admins where aUsername = '$username'");
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);
Not a great way of doing this but you should be able to get it working by adding global to your method/function:
function get_user($username) {
global $db;
$query = $db->query("select aUsername,aPassword,aOnline,aLastlogin from tbl_admins where aUsername = '$username'");
...
}
Working with globals this way you need to be very careful that you don't overwrite the variable at any point.