扩展MySQLi类

ben*_*nnn 2 php mysqli class

我希望能够创建扩展MySQLi类的类来执行所有SQL查询.

$mysql = new mysqli('localhost', 'root', 'password', 'database') or die('error connecting to the database');
Run Code Online (Sandbox Code Playgroud)

我不知道如何在没有全局化$ mysql对象的情况下执行此操作以在我的其他方法或类中使用.

class Blog {

public function comment() {
    global $mysql;

    //rest here
}

}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.

谢谢.

Yad*_*ada 12

我正在做类似的事情.我对这个封装数据库登录的单例类感到高兴.

<?php
class db extends mysqli
{
    protected static $instance;
    protected static $options = array();

    private function __construct() {
        $o = self::$options;

        // turn of error reporting
        mysqli_report(MYSQLI_REPORT_OFF);

        // connect to database
        @parent::__construct(isset($o['host'])   ? $o['host']   : 'localhost',
                             isset($o['user'])   ? $o['user']   : 'root',
                             isset($o['pass'])   ? $o['pass']   : '',
                             isset($o['dbname']) ? $o['dbname'] : 'world',
                             isset($o['port'])   ? $o['port']   : 3306,
                             isset($o['sock'])   ? $o['sock']   : false );

        // check if a connection established
        if( mysqli_connect_errno() ) {
            throw new exception(mysqli_connect_error(), mysqli_connect_errno()); 
        }
    }

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

    public static function setOptions( array $opt ) {
        self::$options = array_merge(self::$options, $opt);
    }

    public function query($query) {
        if( !$this->real_query($query) ) {
            throw new exception( $this->error, $this->errno );
        }

        $result = new mysqli_result($this);
        return $result;
    }

    public function prepare($query) {
        $stmt = new mysqli_stmt($this, $query);
        return $stmt;
    }    
}
Run Code Online (Sandbox Code Playgroud)

要使用你可以有这样的东西:

<?php
require "db.class.php";

$sql = db::getInstance();

$result = $sql->query("select * from city");

/* Fetch the results of the query */ 
while( $row = $result->fetch_assoc() ){ 
    printf("%s (%s)\n", $row['Name'], $row['Population']); 
} 
?>
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个类作为Singleton的一个例子,但是由于需要重写`query()`和`prepare()`,因为`mysqli`OO API已经提供了这些. (3认同)