MySQLDB.class.php
<?php /**
* 数据库操作工具类
*/
class MySQLDB {
// 定义相关属性
private $host;// 主机地址
private $port;// 端口号
private $user;// 用户名
private $pass;// 用户密码
private $charset;// 字符集
private $dbname;// 数据库名
private $link;// 运行的时候需要的属性,保存连接资源
// 增加私有属性,用户保存单例对象
private static $instance;
/**
* 构造方法
* @param array $config
*/
public function __construct($config) {
// 初始化相关属性
$this->initParams($config);
// 连接数据库
$this->my_connect();
}
/**
* 初始化相关属性
* @param array $config
*/
private function initParams($config) {
$this->host = isset($config['host']) ? $config['host'] : 'localhost';
$this->port = isset($config['port']) ? $config['port'] : '';
$this->user = isset($config['user']) ? $config['user'] : 'root';
$this->pass = isset($config['pass']) ? $config['pass'] : '';
$this->charset = isset($config['charset']) ? $config['charset'] : 'utf8';
$this->dbname = isset($config['dbname']) ? $config['dbname'] : 'test';
}
/**
* 连接数据库
*/
private function my_connect() {
if($link = mysqli_connect($this->host, $this->user, $this->pass, $this->dbname)) {
// 连接成功,应该将链接资源保存到属性中
$this->link = $link;
}else {
// 连接失败
echo '数据库连接失败!<br />';
echo '错误代码:',mysql_errno(),'<br />';
echo '错误信息:',mysql_error(),'<br />';
return false;
}
}
}
test.php
<?php header('Content-type:text/html;Charset=utf-8');
// 载入数据库工具类
include './MySQLDB.class.php';
//设置相关的属性
$config = array(
'pass' => '',
'dbname' => 'dbo'
);
//实例化一个对象
$db = new MySQLDB($config);
$sql = "select * from `dbo`.optiobookigtools_user";
$result = mysqli_query($db,$sql);
// 返回记录数
$rowcount=mysqli_num_rows($result);
printf("总共返回 %d 行数据。",$rowcount);
// 释放结果集
var_dump(mysqli_free_result($result));