调用成员函数prepare()对代码上的非对象错误进行协助

时间:2014-03-17 09:13:15

标签: php

<?php
class DB {
    private static $_instance = null; 
    private $_pdo,
            $_query,
            $_error = false,
            $_results,
            $_count = 0;
    private function  __construct() {
        try{
            $this-> pdo = new PDO('mysql:host-'. Config::get('mysql/host') . ';dbname-'. Config::get('mysql/db'), Config::get('mysql/username'),Config::get('mysql/password'));
        } catch (PODException $e){
            die($e->getMessage());
        }  
    }
public static function getInstance() {
    if(!isset(self::$_instance)) {
        self::$_instance = new DB();
    }
    return self::$_instance;

}

public function query( $sql, $params = array()) {
    $this->_error = false;
    if($this->_query = $this->_pdo->prepare($sql)) {
        echo 'success';

    }
}

    }  

1 个答案:

答案 0 :(得分:0)

将此代码更改为。

function db()
{
    static $db;
    if (!$db)
    {
        $dsn = 'mysql:host'.Config::get('mysql/host').';dbname'.Config::get('mysql/db');
        $db = new PDO($dsn, Config::get('mysql/username'),Config::get('mysql/password'));
        $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    }
    return $db;
}

然后叫它

$stmt = db()->prepare($sql);