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

前端 未结 3 1681
遇见更好的自我
遇见更好的自我 2021-01-28 16:00

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\');
         


        
3条回答
  •  被撕碎了的回忆
    2021-01-28 16:08

    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'");
    

提交回复
热议问题