1 <?php
2 /**
3 * Author: suvan
4 * CreateTime: 2018/2/27
5 * description: 数据库操作类(仅对接MySQL数据库,主要利用MySQLi函数)
6 */
7 class Database{
8
9 //MySQL主机地址
10 private $_host;
11 //MySQL用户名
12 private $_user;
13 //MySQL用户密码
14 private $_password;
15 //指定数据库名称
16 private $_database;
17 //MySQL数据库端口号
18 private $_port;
19 private $_socket;
20 //当前数据库对象
21 private $_dbObj;
22 //数据库表
23 private $_table;
24 //数据库表对象
25 private $_tableObj;
26 // 最近错误信息
27 protected $error = '';
28 // 数据信息
29 protected $data = array();
30 // 查询表达式参数
31 protected $options = array();
32 protected $_validate = array(); // 自动验证定义
33 protected $_auto = array(); // 自动完成定义
34 protected $_map = array(); // 字段映射定义
35 protected $_scope = array(); // 命名范围定义
36 // 链操作方法列表
37 protected $methods = array('strict','order','alias','having','group','lock','distinct','auto','filter','validate','result','token','index','force');
38
39 /**
40 * Database类初始化函数
41 * 取得DB类的实例对象 字段检查
42 * @access public
43 * @param string $host MySQL数据库主机名
44 * @param string $user MySQL数据库用户名
45 * @param string $password MySQL数据库密码
46 * @param string $database 指定操作的数据库
47 * @return mixed 数据库连接信息、错误信息
48 */
49 public function __construct($host,$user,$passowrd,$database,$port=3306){
50 $this->_initialize();
51 if(!isset($host)||!isset($user)||!isset($passowrd)||!isset($database)){
52 return false;
53 }else{
54 $this->_host = $host;
55 $this->_user = $user;
56 $this->_password = $passowrd;
57 $this->_database = $database;
58 $this->_port = $port;
59 $_dbObj = new mysqli($host,$user,$passowrd,$database,$port);
60 if($_dbObj->connect_errno){
61 $this->error = $_dbObj->connect_error;
62 return false;
63 }else{
64 $this->_dbObj = $_dbObj;
65 return $this;
66 }
67 }
68 }
69 /**
70 * 错误信息函数
71 * 返回数据库操作过程中最后一次执行时的错误信息
72 * @access public
73 * @return mixed 数据库连接错误信息(正常返回'')
74 */
75 public function error(){
76 return $this->error;
77 }
78 // 回调方法 初始化模型
79 protected function _initialize() {}
80 /**
81 * 设置数据对象的值
82 * @access public
83 * @param string $name 名称
84 * @param mixed $value 值
85 * @return void
86 */
87 public function __set($name,$value) {
88 // 设置数据对象属性
89 $this->data[$name] = $value;
90 }
91
92 /**
93 * 获取数据对象的值
94 * @access public
95 * @param string $name 名称
96 * @return mixed
97 */
98 public function __get($name) {
99 return isset($this->data[$name])?$this->data[$name]:null;
100 }
101
102 /**
103 * 检测数据对象的值
104 * @access public
105 * @param string $name 名称
106 * @return boolean
107 */
108 public function __isset($name) {
109 return isset($this->data[$name]);
110 }
111
112 /**
113 * 销毁数据对象的值
114 * @access public
115 * @param string $name 名称
116 * @return void
117 */
118 public function __unset($name) {
119 unset($this->data[$name]);
120 }
121 /**
122 * 利用__call方法实现一些特殊的方法(对于调用类中不存在方法的解决方案)
123 * @access public
124 * @param string $method 方法名称
125 * @param array $args 调用参数
126 * @return mixed
127 */
128 public function __call($method,$args) {
129 /*if(in_array(strtolower($method),$this->methods,true)) {
130 // 连贯操作的实现
131 $this->options[strtolower($method)] = $args[0];
132 return $this;
133 }elseif(in_array(strtolower($method),array('count','sum','min','max','avg'),true)){
134 // 统计查询的实现
135 $field = isset($args[0])?$args[0]:'*';
136 return ;
137 }elseif(strtolower(substr($method,0,5))=='getby') {
138 // 根据某个字段获取记录
139 $field = parse_name(substr($method,5));
140 $where[$field] = $args[0];
141 return ;
142 }elseif(strtolower(substr($method,0,10))=='getfieldby') {
143 // 根据某个字段获取记录的某个值
144 $name = parse_name(substr($method,10));
145 $where[$name] =$args[0];
146 return ;
147 }elseif(isset($this->_scope[$method])){// 命名范围的单独调用支持
148 return ;
149 }else{
150
151 }*/
152 }
153 /*
154 * 选择数据库
155 * @access public
156 * @param string $database 选择的数据库名称
157 * @return mixed 数据库连接信息
158 * */
159 public function select_db($database){
160 $select_db = mysqli_select_db($this->_dbObj,$database);
161 if($select_db){
162 $this->_database = $database;
163 $_dbObj = new mysqli($this->_host,$this->_user,$this->_password,$database,$this->_port);
164 $this->_dbObj = $_dbObj;
165 return $this;
166 }else{
167 $this->error = mysqli_error($this->_dbObj);
168 return false;
169 }
170 }
171 /*
172 * 数据库用户更换
173 * @access public
174 * @param string $user 数据库用户名称
175 * @param string $password 数据库用户密码
176 * @return mixed 数据库连接信息
177 * */
178 public function change_user($user,$password){
179 $change_user = mysqli_change_user($this->_dbObj,$user,$password,$this->_database);
180 if($change_user){
181 $this->_user = $user;
182 $this->_password = $password;
183 $_dbObj = new mysqli($this->_host,$this->_user,$this->_password,$this->_database,$this->_port);
184 $this->_dbObj = $_dbObj;
185 return $this;
186 }else{
187 $this->error = mysqli_error($this->_dbObj);
188 return false;
189 }
190 }
191 /*
192 * 查询数据库中所有的表名
193 * @access public
194 * @return array 数据表的数量和表名
195 * */
196 public function tables(){
197 $sql = 'show tables';
198 $search_res = mysqli_query($this->_dbObj,$sql);
199 if($search_res){
200 $num_rows = $search_res->num_rows;
201 $tables_msg = array(
202 'count'=>$num_rows,
203 'tables'=>array()
204 );
205 for($i=0;$i<$num_rows;$i++){
206 $row = $search_res->fetch_assoc();
207 $key = 'Tables_in_'.$this->_database;
208 array_push($tables_msg['tables'],$row[$key]);
209 }
210 mysqli_free_result($search_res);
211 return $tables_msg;
212 }else{
213 mysqli_free_result($search_res);
214 return false;
215 }
216 }
217 /*
218 * 获取指定表中所有信息
219 * @access public
220 * @param string $table 数据表名称
221 * @return array 数据表的详细信息
222 * */
223 public function select_table($table){
224 $sql = 'select * from '.$table;
225 $search_res = mysqli_query($this->_dbObj,$sql);
226 if($search_res){
227 $this->_table = $table;
228 $table_msg = self::query_handle($search_res);
229 $this->_tableObj = $table_msg;
230 mysqli_free_result($search_res);
231 return $table_msg;
232 }else{
233 mysqli_free_result($search_res);
234 return false;
235 }
236 }
237 /*
238 * 获取指定表的字段详细信息
239 * @access public
240 * @param string $table 数据表名称
241 * @return array 数据表的字段详细信息
242 * */
243 public function select_table_fields($table){
244 $sql = 'show fields from '.$table;
245 $search_res = mysqli_query($this->_dbObj,$sql);
246 if($search_res){
247 $this->_table = $table;
248 $fields_msg = self::query_handle($search_res);
249 mysqli_free_result($search_res);
250 return $fields_msg;
251 }else{
252 mysqli_free_result($search_res);
253 return false;
254 }
255 }
256 /*
257 * 获取数据表中指定字段信息(允许多字段同时查询)
258 * @access public
259 * @param mixed $field 指定字段(字符串传入使用,间隔)
260 * @return array 数据表中指定字段信息
261 * */
262 public function getField($field){
263 $fields = self::param_handle($field);
264 $count = count($fields);
265 for($i=0;$i<$count;$i++){
266 $index = $fields[$i];
267 $sql = 'select '.$index.' from '.$this->_table;
268 $res = mysqli_query($this->_dbObj,$sql);
269 $field_msg[$index] = self::query_handle($res);
270 }
271 return $field_msg;
272 }
273 /*
274 * mysqli_query函数结果处理函数
275 * @access protected
276 * @param object $obj mysqli_query函数结果
277 * @return array 数据表中指定字段信息
278 * */
279 protected function query_handle($obj){
280 $res = array();
281 for($i=0;$i<$obj->num_rows;$i++){
282 $row = $obj->fetch_assoc();
283 array_push($res,$row);
284 }
285 return $res;
286 }
287 /*
288 * 传入参数处理函数
289 * @access protected
290 * @param mixed $param 传入参数
291 * @return array 处理后数组数据
292 * */
293 public function param_handle($param){
294 if(is_string($param)&&!empty($param)){
295 $params = explode(',',$param);
296 }elseif(is_array($param)&&!empty($param)){
297 $params = $param;
298 }else{
299 return false;
300 }
301 return $params;
302 }
303 /*
304 * 查询表达式参数处理函数
305 * @access protected
306 * @param mixed $param 传入参数(where limit order)
307 * @return string 处理后字符串数据
308 * */
309 public function options_handle($param){
310 if(is_numeric($param)){
311 $option = $param;
312 }elseif(is_string($param)&&!empty($param)&&!is_numeric($param)){
313 $params = explode(',',$param);
314 $count = count($params);
315 $option = implode(' and ',$params);
316 }elseif(is_array($param)&&!empty($param)){
317 $params = $param;
318 $count = count($params);
319 $arr = array();
320 foreach($param as $key=>$value){
321 $tip = "$key=$value ";
322 array_push($arr,$tip);
323 }
324 $option = implode(' and ',$arr);
325 }else{
326 return false;
327 }
328 return $option;
329 }
330 /*
331 * 查询表达式$options处理函数
332 * @access protected
333 * @return string 处理后字符串数据
334 * */
335 protected function option(){
336 $options = $this->options;
337 $option = '';
338 if(isset($options['where'])){
339 $option .= 'where '.$options['where'].' ';
340 }
341 if(isset($options['order'])){
342 $option .= 'order by '.$options['order'].' '.$options['order_type'].' ';
343 }
344 if(isset($options['limit'])){
345 $option .= 'limit '.$options['limit'];
346 }
347 return $option;
348 }
349 /*
350 * 根据查询表达式查询数据(符合条件的所有记录)
351 * @access public
352 * @return array 满足查询表达式的特定数据
353 * */
354 public function find(){
355 $option = self::option();
356 $sql = 'select * from '.$this->_table.' '.$option;
357 $search_res = mysqli_query($this->_dbObj,$sql);
358 $msg = self::query_handle($search_res);
359 return $msg;
360 }
361 /*
362 * 查询表达式 where处理函数
363 * @access public
364 * @param mixed $where where查询条件
365 * @return object $this
366 * */
367 public function where($where){
368 $this->options['where'] = self::options_handle($where);
369 return $this;
370 }
371 /*
372 * 查询表达式 limit处理函数
373 * @access public
374 * @param mixed $limit limit查询条件(数字)
375 * @return object $this
376 * */
377 public function limit($limit){
378 $this->options['limit'] = self::options_handle($limit);
379 return $this;
380 }
381 /*
382 * 查询表达式 order处理函数
383 * @access public
384 * @param string $order order查询条件
385 * @param string $type order查询条件的顺序(默认降序)
386 * @return object $this
387 * */
388 public function order($order,$type='desc'){
389 $this->options['order'] = $order;
390 $this->options['order_type'] = $type;
391 return $this;
392 }
393 /*
394 * 数据处理函数(最多处理二维数据)
395 * @access public
396 * @param array $data 需要插入的数据
397 * @return object $this
398 * */
399 public function data(array $data){
400 $values = array();
401 $fields = array();
402 if(is_array($data)){
403 foreach($data as $key=>$value){
404 if(is_array($value)){ //二维数组
405 $tip = 1;
406 array_push($values,'('.implode(',',array_values($value)).')');
407 array_push($fields,'('.implode(',',array_keys($value)).')');
408 }else{ //一维数组
409 $tip = 0;
410 }
411 }
412 }else{
413 return false;
414 }
415 if(!$tip){
416 array_push($values,'('.implode(',',array_values($data)).')');
417 array_push($fields,'('.implode(',',array_keys($data)).')');
418 }
419 $this->data['fields'] = $fields[0];
420 $this->data['values'] = implode(',',$values);
421 return $this;
422 }
423 /*
424 * 数据新增函数
425 * @access public
426 * @return mixed 数据库新增信息
427 * */
428 public function add(){
429 $fields = $this->data['fields'];
430 $values = $this->data['values'];
431 $sql = 'INSERT INTO '.$this->_table.$fields.'VALUES'.$values;
432 $res = mysqli_query($this->_dbObj,$sql);
433 return $res;
434 }
435 /*
436 * 数据更新函数(一维数组)
437 * @access public
438 * @param array $data 需要更新的数据
439 * @return mixed 数据库新增信息
440 * */
441 function save(array $data){
442 $tip = array();
443 if(is_array($data)){
444 foreach($data as $key=>$value){
445 array_push($tip,"$key=$value");
446 }
447 }else{
448 return false;
449 }
450 $set_msg = implode(',',$tip);
451 $sql = 'UPDATE '.$this->_table.' SET '.$set_msg.' WHERE '.$this->options['where'];
452 $res = mysqli_query($this->_dbObj,$sql);
453 return $res;
454 }
455 /*
456 * 数据删除函数
457 * @access public
458 * @return mixed 数据库删除信息
459 * */
460 public function delete(){
461 $sql = 'DELETE FROM '.$this->_table.' WHERE '.$this->options['where'];
462 $res = mysqli_query($this->_dbObj,$sql);
463 return $res;
464 }
465 /*
466 * SQL语句查询
467 * */
468 public function query($sql){
469 $search_res = mysqli_query($this->_dbObj,$sql);
470 return $search_res;
471 }
472 /*
473 * mysql中查询语句
474 * */
475 protected function sql(){
476 /*
477 * 基本SQL语句
478 * 插入数据:INSERT INTO tb_name(id,name,score)VALUES(NULL,'张三',140),(NULL,'张四',178),(NULL,'张五',134);
479 * 更新语句:UPDATE tb_name SET score=189 WHERE id=2;
480 * 删除数据:DELETE FROM tb_name WHERE id=3;
481 * WHERE语句:SELECT * FROM tb_name WHERE id=3;
482 * HAVING 语句:SELECT * FROM tb_name GROUP BY score HAVING count(*)>2
483 * 相关条件控制符:=、>、<、<>、IN(1,2,3......)、BETWEEN a AND b、NOT AND 、OR Linke()用法中 % 为匹配任意、 _ 匹配一个字符(可以是汉字)IS NULL 空值检测
484 * MySQL的正则表达式:SELECT * FROM tb_name WHERE name REGEXP '^[A-D]' //找出以A-D 为开头的name
485 * */
486 }
487 /*
488 * 关闭连接
489 * */
490 public function close(){
491 $close = mysqli_close($this->_dbObj);
492 if($close){
493 return true;
494 }else{
495 return false;
496 }
497 }
498 function __destruct(){
499 mysqli_close($this->_dbObj);
500 }
501 }