1.1.1 思路
1、 单例模式
2、 连接数据库
a) 初始化参数
b) 连接数据库
3、 对数据表操作
a) 数据操作语句(insert、delete、update)
b) 数据查询语句(select)
i. 匹配二维数组
ii. 匹配一条记录(返回一维数组)
iii. 匹配一行一列
1.1.2 原则
为了发挥代码的可重用性,每个方法只做一个功能。不要将多个功能封装到一个方法中。
1.1.3 代码实现
<?php
class MySQLDB {
private $host; //主机地址
private $user; //用户名
private $pwd; //密码
private $dbname; //数据库名
private $port; //端口号
private $charset; //字符编码
private $link; //连接对象
private static $instance; //保存MySQLDB的单例
private function __construct($param) {
$this->initParam($param);
$this->initConnect();
}
private function __clone() {
}
public static function getInstance($param=array()) {
if(!self::$instance instanceof self)
self::$instance=new self($param);
return self::$instance;
}
//初始化参数
private function initParam($param) {
$this->host=$param['host']??'127.0.0.1';
$this->user=$param['user']??'root';
$this->pwd=$param['pwd']??'root';
$this->dbname=$param['dbname']??'php15';
$this->port=$param['port']??3306;
$this->charset=$param['charset']??'utf8';
}
//连接数据库
private function initConnect() {
$this->link=@mysqli_connect($this->host,$this->user,$this->pwd,$this->dbname,$this->port);
if(mysqli_connect_error()){
echo '数据库连接失败<br>';
echo '错误信息:'.mysqli_connect_error(),'<br>';
echo '错误码:'.mysqli_connect_errno(),'<br>';
exit;
}
mysqli_set_charset($this->link,$this->charset);
}
//*************************SQL操作****************************************
/**
*执行SQL操作语句
*执行数据操作语句(insert,update,delete)成功返回受影响的记录数,失败返回false
*执行数据查询语句(select),返回结果集
*/
public function execute($sql) {
if(!$rs=mysqli_query($this->link,$sql)){
echo 'SQL语句执行失败<br>';
echo '错误信息:'.mysqli_error($this->link),'<br>';
echo '错误码:'.mysqli_errno($this->link),'<br>';
echo '错误的SQL语句是:'.$sql,'<br>';
exit;
}
return $rs;
}
/**
*返回所有记录,二维数组
*$param $type string assoc|row|array
*/
public function fetchAll($sql,$type='assoc') {
$rs=$this->execute($sql); //获取结果集
if(!in_array($type,array('assoc','row','array')))
$type='assoc';
$fn='mysqli_fetch_'.$type; //拼接匹配函数名
$array=array(); //保存结果的数组
while($rows=$fn($rs)){ //将结果转成二维数组
$array[]=$rows;
}
return $array;
}
//返回一条记录,一维数组
public function fetchRow($sql,$type='assoc') {
if($rs=$this->fetchAll($sql,$type))
return $rs[0];
return null;
}
//返回第一行的第一列
public function fetchColumn($sql) {
if($rs=$this->fetchRow($sql,'row'))
return $rs[0];
return null;
}
}
//测试
$param=array(
'user' => 'root',
'pwd' => 'root',
'dbname' => 'jokedb',
);
$db=MySQLDB::getInstance($param);
//$db->execute("insert into title values (null,'aa')");
//$db->execute("update title set title='bbb' where id=19");
//$db->execute('delete from title where id=19');
//$rs=$db->fetchAll('select * from title','aa');
//$rs=$db->fetchRow('select * from title where id=100');
$rs=$db->fetchColumn('select count(*) from title');
echo '<pre>';
print_r($rs);