<?php
//使用三私一公的单例模式实现DAOMySQLi工具类
class DAOMySQLi
{
private $host;
private $user;
private $pass;
private $dbname;
private $port;
//保存mysqli对象
private $MySQLi;
//一个私有静态属性
private static $instance;
//私有构造方法
private function __construct($options)
{
$this->host = $options['host'];
$this->user = $options['user'];
$this->pass = $options['pass'];
$this->dbname = $options['dbname'];
$this->port = $options['port'];
$this->MySQLi = new MySQLi($this->host,$this->user,$this->pass,$this->dbname,$this->port);
//设置字符集
$this->MySQLi->query('SET NAMES UTF8;');
}
//私有克隆方法
private function __clone(){}
//公有方法
public static function getSingleton($options)
{
//判断一下实例化的对象是否为这个类的
if(!self::$instance instanceof self)
{
self::$instance = new self($options);
}
return self::$instance;
}
//查询所有语句
public function fetchAll($sql)
{
//执行语句
$res = $this->MySQLi->query($sql);
if($res)
{
$rows = [];
while($row = $res->fetch_assoc())
{
$rows[] = $row;
}
//清空结果集
$res->free();
return $rows;
}
else
{
//说明sql语句有误
echo 'SQL语句有误,详细信息如下:<br>'.$this-> MySQLi -> error;
exit();
}
}
//查询一条语句
public function fetchOne($sql)
{
//执行语句
$res = $this->MySQLi->query($sql);
if($res)
{
$row = $res->fetch_assoc();
$res->free();
return $row;
}
else
{
//说明sql语句有误
echo 'SQL语句误,详细信息如下:<br>'.$this-> MySQLi -> error;
exit();
}
}
//DML(删除,添加,修改)语句
public function DML($sql)
{
$res = $this->MySQLi->query($sql);
if($res)
{
$affected_rows = $this->MySQLi->affected_rows;
if($affected_rows>0)
{
return true;
}
else
{
return false;
}
}
else
{
//说明sql语句有误
echo 'SQL语句有误,详细信息如下:<br>'.$this-> MySQLi -> error;
exit();
}
}
}
总结:使用单例模式使连接数据库的对象不能重复实例化,提高效率。通过将sql语句封装到类的方法中在外实例化后,可以调用该方法,来执行,大大减少代码。
下面给出查询语句调用示意代码,其他基本类似。
<?php
require_once './hw_DAOMySQLi.php';
$options=[
'host'=>'localhost',
'user'=>'root',
'pass'=>'wasd',
'dbname'=>'stu',
'port'=>3306
];
$MySQLi = DAOMySQLi::getSingleton($options);
//sql查询
$sql = "SELECT * FROM grade;";
$rows = $MySQLi->fetchAll($sql);
include_once './stu_lst.html';
?>