在课堂上使用MySQLi,如何实现?

时间:2011-02-24 18:31:57

标签: php database oop mysqli

直到现在我通过$database中的参数传递了__constructor - 对象 但我想摆脱每一堂课的传球。但怎么办呢?我不是一个非常聪明的操作员,我知道一些基础知识...... 这是我现在使用的代码:更新

class connection {
    public static $connection;

    public function __construct() {
        $this->connection = new MySQLi('localhost', 'user', 'pass');
        $this->connection->select_db('database');
    }

    public function getInstance() {
        if(!isset(self::$connection)) {
            self::$connection = new connection;
        }
        return self::$connection;
    }
}

class something {
    private $connection;

    public $id;

    function __construct($id) {
        $this->connection = connection::getInstance();
        $this->id = $id;
    }

    function verify() {
        $statement = $this->connection->prepare('SELECT * FROM `tabel` WHERE `id` = ?');
        $statement->bind_param('s', $this->id);
        $statement->execute();

        $statement->store_result();
        if($statement->num_rows != 1) {
            return false;
        }
    }
}

不起作用:Call to undefined method connection::prepare()

1 个答案:

答案 0 :(得分:1)

MySQLi::getInstance($optional_instance_name)作为静态方法,检索您要求的任何数据库连接。