1<?php 2 3 //DAOMySQLI.class.php 4 5 //完成对mysql数据库操作,单例模式 6 7 //开发类 8 //1. 定类名 9 //2. 定成员属性 10 //3. 定成员方法[查询,dml操作] 11 12 final class DAOMySQLi{ 13 14 // 将成员属性以 _开头是一种命名风格. 老外比较喜欢. 15 //主机名 16 private $_host; 17 private $_user; 18 private $_pwd; 19 private $_dbname; 20 private $_port; 21 private $_charset; 22 23 //因为我们做成单例 24 // $_instance : 表示DAOMySQLi 的一个对象实例 25 private static $_instance; 26 27 // 有个mysqli连接[对象] 28 private $_mySQLi; 29 30 //定构造方法. 31 //option : 选项 32 private function __construct(array $option){ 33 34 //初识化数据库属性 35 $this->_initOption($option); 36 37 //初始化_mySQLi属性 38 $this->_initMySQLi(); 39 40 } 41 42 private function _initMySQLi(){ 43 44 //初始化我们的 _mySQLi 45 $this->_mySQLi = new MySQLi($this->_host, $this->_user, $this->_pwd, $this->_dbname, $this->_port); 46 47 if($this->_mySQLi->connect_errno){ 48 49 die('连接失败 , 错误信息时候' . $this->_mySQLi->connect_error); 50 } 51 52 //设置字符集 53 $this->_mySQLi->set_charset($this->_charset); 54 55 } 56 57 //一个函数,用于初始化连接数据库选项 58 private function _initOption(array $option){ 59 60 //验证数据 61 $this->_host = isset($option['host'])? $option['host'] : ''; 62 $this->_user = isset($option['user'])? $option['user'] : ''; 63 $this->_pwd = isset($option['pwd'])? $option['pwd'] : ''; 64 $this->_dbname = isset($option['dbname'])? $option['dbname'] : ''; 65 $this->_port = isset($option['port'])? $option['port'] : ''; 66 $this->_charset = isset($option['charset'])? $option['charset'] : ''; 67 68 if($this->_host == '' || $this->_user == '' || $this->_pwd == '' || $this->_dbname == '' || $this->_port == '' || $this->_charset == ''){ 69 die('参数传入有误!'); 70 } 71 72 } 73 74 //定义一个静态方法 getSingleton.. 75 public static function getSingleton(array $option){ 76 77 //判断是否已经有对象实例 78 if(!self::$_instance instanceof self){ 79 //创建一个对象 80 self::$_instance = new self($option); 81 } 82 return self::$_instance; 83 } 84 85 //防止克隆 86 private function __clone(){} 87 88 //编写一个成员方法,完成对数据表的查询 89 public function fetchAll($sql){ 90 91 //定义一个空数组[封装数据] 92 $arr = array(); 93 94 if($res = $this->_mySQLi->query($sql)){ 95 96 //{把 $res 对象返回给调用者 97 //问题1. 一般情况下,我们程序员希望将$res对象尽快释放. 98 //解决思路: 99 //(1)$res ==数据===>$arr 100 while($row = $res->fetch_assoc()){ 101 $arr[] = $row; 102 } 103 //(2)释放$res 104 $res->free(); 105 //(3)返回数组 106 return $arr; 107 108 }else{ 109 //失败 110 echo '<br> 执行失败 sql语句是' . $sql; 111 echo '<br> 失败的原因是 ' . $this->_mySQLi->error; 112 exit; 113 } 114 } 115 116 //编写一个方法,完成对表的dml操作 117 public function query($sql){ 118 119 if($this->_mySQLi->query($sql)){ 120 121 return true; 122 }else{ 123 //失败 124 echo '<br> 执行失败 sql语句是' . $sql; 125 echo '<br> 失败的原因是 ' . $this->_mySQLi->error; 126 exit; 127 } 128 } 129 130 } 131 132?>
DAOMYSQLI工具类
Wesley13
2021-10-11
1179 0 0
点赞
收藏
评论区
加载中...