Working with PDO object - MySQL -


i new pdo , have pretty simple question. have simple function connecting 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 function connect db. later when trying send query using $dbh->query got "call member function query() on non-object ". understand - don't have instance of class @ moment. think achieve use $dbh = new pdo("settings") again, kind of stupid isn't? function has no sense than. tried return $dbh in connectdb function (before null statement) wasn't working.

how should done properly?

it depends on app's architecture, believe, should make database handle class variable, initialize in constructor , use 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 removed "= null" part         } catch (pdoexception $e) {             print "error!: " . $e->getmessage() . "<br/>";             die();         }     }      public function getsomething(){         //run query here:         return $this->_db->query('');     } } 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -