Working with PDO object - MySQL
I am new to PDO and I have pretty simple 开发者_JAVA百科question. I have a simple function for connecting to DB:
function connectDB()
{
try {
$dbh = new PDO('mysql:host='.Config::$db_server.';dbname='.Config::$db_name, Config::$db_login, Config::$db_password, array(
PDO::ATTR_PERSISTENT => true
));
$dbh->exec("SET CHARACTER SET utf8");
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
After calling this function I successfully connect to db. Later when trying to send a query using $dbh->query I got "Call to a member function query() on a non-object ". I do understand that - I don't have an instance of the class at the moment. But the only think to achieve that is to use $dbh = new PDO("settings") again, which is kind of stupid isn't? The function has no sense than. I tried to return the $dbh in the connectDB function (before the NULL statement) but it wasn't really working.
How should be this done properly?
It depends on your app's architecture, but I believe, you should make database handle a class variable, initialize it in constructor and use it later.
class DatabaseAccess{
private $_db;
public function __construct(){
try {
$this->_db = new PDO('mysql:host='.Config::$db_server.';dbname='.Config::$db_name, Config::$db_login, Config::$db_password, array(
PDO::ATTR_PERSISTENT => true
));
$this->_db->exec("SET CHARACTER SET utf8");
//notice I removed "= null" part
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
public function getSomething(){
//run your query here:
return $this->_db->query('');
}
}
You need to remove the $dbh = null;
sentence in your function. With this sentence you are overwriting the connection with a null value, so anytime later you do $dbh->query()
, it's like doing null->query()
, and so that error appears.
Also, you need to save the handler, or it gets lost after your code exits that function. Add a return $dbh;
at the end of your function or wrap it in a class.
精彩评论