<?php
final class DAOMySQLi
{
//将 <成员属性> 以 _ 开头是一种命名风格
private $_host;
private $_user;
private $_pwd;
private $_dbname;
private $_port;
private $_charset;
//标识DAOMySQLi的一个对象实例
private static $_instance;
//连接
private $_mysqli;
/*
* 构造方法
*/
private function __construct(array $option)
{
//验证数据
$this->_host = isset($option['host']) ? $option['host'] : '';
$this->_user = isset($option['user']) ? $option['user'] : '';
$this->_pwd = isset($option['pwd']) ? $option['pwd'] : '';
$this->_dbname = isset($option['dbname']) ? $option['dbname'] : '';
$this->_port = isset($option['port']) ? $option['port'] : '';
$this->_charset = isset($option['charset']) ? $option['charset'] : '';
if($this->_host == '' || $this->_user == ''|| $this->_dbname == '' || $this->_pwd == '' || $this->_port == '' || $this->_charset == ''){
die("传入参数有误<br>");
}
//初始化 _mysqli
$this->_mysqli = new mysqli($this->_host, $this->_user, $this->_pwd, $this->_dbname, $this->_port);
if ($this->_mysqli->connect_errno){
die('连接失败,错误原因:'.$this->_mysqli->connect_error);
}
//设置字符集
$this->_mysqli->set_charset($this->_charset);
}
//定义一个静态方法
public static function getSingleton(array $option){
//判断是否已经有对象实例
//如果没有创建对象实例 就创建一个
if(!self::$_instance instanceof self){
self::$_instance = new self($option);
return self::$_instance;
}
}
/*
*防止克隆
*/
private function __clone()
{
// TODO: Implement __clone() method.}
}
/*
*对数据库的查询方法
*/
//查询返回多条结果
public function fetchAll($sql){
$arr = array();
if($res = $this->_mysqli->query($sql)){
//细节:创建了的结果集要尽快释放,所以在这里将结果集转换成数组 释放结果集 返回数组
while ($row = $res->fetch_assoc()){
$arr[] = $row;
}
$res->free();
return $arr;
}else{
echo '<br> 执行失败 sql语句是'. $sql;
echo '<br> 失败原因:'. $this->_mysqli->error;
exit();
}
}
//查询返回一条结果
public function fetchOne($sql){
if($res = $this->_mysqli->query($sql)){
$arr = $res->fetch_assoc();
}else{
echo '<br> 执行失败 sql语句是'. $sql;
echo '<br> 失败原因:'. $this->_mysqli->error;
exit();
}
$res->free();
return $arr;
}
/*
* 对表的dml操作
*/
public function query($sql){
if($this->_mysqli->query($sql)){
return true;
}else{
echo '<br> 执行失败 sql语句是'. $sql;
echo '<br> 失败原因:'. $this->_mysqli->error;
exit();
}
}
/*
* 查找最新插入的商品id
*/
public function queryMaxId(){
$sql = 'SELECT MAX(id) AS maxid FROM Goods';
$res = $this->_mysqli->query($sql);
if($row = $res->fetch_assoc()){
$maxid = $row['maxid'];
}else{
echo"最新插入的商品id查找失败";
}
return $maxid;
}
}
DAOMySQLi类,方便与数据库交互
最新推荐文章于 2021-03-17 14:57:48 发布