1 <?php2
3 classDb4 {5 static private $config =[6 'datahost' => '', //主机名
7 'dataname' => '', //数据库名
8 'username' => '', //用户名
9 'password' => '', //用户密码
10 'charset' => 'utf8', //默认字符集
11 'prefix' => '', //表前缀
12 'dataport' => '3306', //端口号
13 'returntype'=> MYSQLI_ASSOC,//查询返回的类型,默认是关联数组
14 'pk' => 'id', //默认主键名称
15 ];16 static private $con = null; //mysqli数据库对象
17 static public $obj = null; //Db类对象
18 static private $error= ''; //报错信息
19 static public $data =[20 'name' => '', //表名称
21 'where' => '', //条件
22 'field' => '*', //所需字段
23 'limit' => '', //查询条数
24 'order' => '', //排序
25 'group' => '', //分组
26 'having'=> '', //having
27 'join' => '', //内连接28 // 'leftjoin' => '', // 左连接29 // 'rightjoin'=> '', // 右连接
30 'on' => '', //连接关联字段
31 'sql' => '', //最后一次执行的sql
32 ]; //数据集
33
34 /**35 * 初始化36 */
37 private function__construct()38 {39 //连接数据库操作
40 self::connect();41 }42
43 /**44 * 连接数据库45 */
46 static private functionconnect()47 {48 self::$con = @mysqli_connect(self::$config['datahost'], self::$config['username'], self::$config['password'], self::$config['dataname'], self::$config['dataport']);49 if (! self::$con)50 {51 die('数据库连接失败'.mysqli_connect_error());52 }53 //设置字符集
54 mysqli_set_charset(self::$con, self::$config['charset']);55 }56
57 /**58 * 设置变量59 */
60 public function __set($name, $value)61 {62 if (array_key_exists($name, self::$config))63 {64 self::$config[$name] = $value;65 }66 }67
68 /**69 * 释放变量70 */
71 public function __unset($name)72 {73 if (array_key_exists($name, self::$config))74 {75 unset(self::$config[$name]);76 }77 }78
79 /**80 * 初始化81 * @param array $config 配置文件82 */
83 static public function init($config =[])84 {85 //初始化配置文件
86 self::parseParams($config);87 if (!is_object(self::$obj))88 {89 self::$obj = newself;90 }91 return self::$obj;92 }93
94 /**95 * 设置配置文件96 * @param array $config 配置文件97 */
98 static private function parseParams($config)99 {100 //加载调用时的config配置
101 if (is_array($config))102 {103 foreach ($config as $key => $val)104 {105 if (array_key_exists($key, self::$config))106 {107 self::$config[$key] = $val;108 }109 }110 }111 }112
113 /**114 * 执行一条sql语句115 */
116 static private function query($sql = '')117 {118 if (empty($sql))119 {120 $query = mysqli_query(self::$con, self::$data['sql']);121 }122 else
123 {124 $query = mysqli_query(self::$con, $sql);125 }126 return $query;127 }128
129 /**130 * 释放结果集131 */
132 static private function free($result)133 {134 if (!is_bool($result))135 {136 //释放结果集
137 mysqli_free_result($result);138 //重置所有值
139 foreach (self::$data as $k => $v)140 {141 if ($k == 'field')142 {143 self::$data[$k] = '*';144 }145 else
146 {147 self::$data[$k] = '';148 }149 }150 }151 }152
153 /**154 * 返回INSERT UPDATE DELETE 影响行数155 */
156 static public functionrowNum()157 {158 if (self::$con)159 {160 return mysqli_affected_rows(self::$con);161 }162 }163
164 /**165 * 设置出错信息166 */
167 static public functionsetError()168 {169 if (self::$con)170 {171 self::$error = mysqli_error(self::$con);172 }173 }174
175 /**176 * 设置表名(不带前缀)177 * @param string $table_name 表名称178 */
179 public function name($table_name)180 {181 self::$data['name'] = self::$config['prefix'].$table_name;182 return self::$obj;183 }184
185 /**186 * 设置表名(带前缀)187 * @param tring $table_name 表名称188 */
189 public function table($table_name)190 {191 self::$data['name'] = $table_name;192 return self::$obj;193 }194
195 /**196 * 需要的字段197 * @param string $value 需要字段,如id,username,password198 */
199 public function field($value)200 {201 self::$data['field'] = " {$value} ";202 return self::$obj;203 }204
205 /**206 * 获取指定记录207 * @param int $star 开始位置208 * @param int $end 结束位置209 */
210 public function limit($star, $end = '')211 {212 if (!empty($end))213 {214 self::$data['limit'] = " LIMIT {$star},{$end} ";215 }216 else
217 {218 self::$data['limit'] = " LIMIT {$star} ";219 }220 return self::$obj;221 }222
223 /**224 * 查询的条件225 * @param string 查询的条件,如:id='32' AND username='test'226 */
227 public function where($value)228 {229 if (!empty($value) && is_string($value))230 {231 self::$data['where'] = " WHERE {$value} ";232 }233 return self::$obj;234 }235
236 /**237 * 内联接238 */
239 public function join($value, $method = 'join')240 {241 if (!empty($value))242 {243 switch(strtolower($method))244 {245 case 'join':
246 default:
247 self::$data['join'] = " JOIN {$value} ";248 break;249 case 'ljoin':
250 self::$data['join'] = " LEFT JOIN {$value} ";251 break;252 case 'rjoin':
253 self::$data['join'] = " RIGHT JOIN {$value} ";254 break;255 }256
257 }258 return self::$obj;259 }260
261 /**262 * 联接查询绑定263 */
264 public function on($value)265 {266 if (!empty($value))267 {268 self::$data['on'] = " ON {$value} ";269 }270 return self::$obj;271 }272
273 /**274 * having 筛选275 */
276 public function having($value)277 {278 //279 return self::$obj;280 }281
282 /**283 * 字段排序284 * @param string $value 排序的字段和排序方式,如:id desc,username asc285 */
286 public function order($value)287 {288 if (!empty($value))289 {290 self::$data['order'] = " ORDER BY {$value} ";291 }292 return self::$obj;293 }294
295 /**296 * 分组297 * @param string $value 字段分组,如:id,username298 */
299 public function group($value)300 {301 if (!empty($value))302 {303 self::$data['group'] = " GROUP BY {$value} ";304 }305 return self::$obj;306 }307
308 /**309 * 删除310 */
311 public functiondelete()312 {313 if (!empty(self::$data['where']))314 {315 self::$data['sql'] = "DELETE FROM `".self::$data['name']."`".self::$data['where'];316 $query = self::query();317
318 if (is_bool($query))319 {320 self::free($query);321 return self::rowNum(); //返回0表示没有行数影响,执行时成功的,返回>0的数字表示影响行数
322 }323 else
324 {325 self::setError(); //设置错误信息
326 return false;327 }328 }329 return false; //没有带条件的删除不能成功
330
331 }332
333 /**334 * 更新335 */
336 public function save($value)337 {338 if (is_string($value))339 {340 if (!empty(self::$data['where']))341 {342 self::$data['sql'] = "UPDATE `".self::$data['name']."` SET ".$value.self::$data['where'];343 $query = self::query();344
345 if (is_bool($query))346 {347 self::free($query);348 return self::rowNum(); //返回0表示没有行数影响,执行时成功的,返回>0的数字表示影响行数
349 }350 else
351 {352 self::setError(); //设置错误信息
353 return false;354 }355 }356 else
357 {358 return false; //没有带条件的更新不能成功
359 }360 }361 }362
363 /**364 * 新增(可以传两种值,一种是数组,一种是字段和对应的值)365 * 数组:$data['username'] = 'abcd' 或 $data = ['username'=>'abcd']366 * 键值:'username', "'abcd'"367 */
368 public functioninsert()369 {370 if (func_num_args() === 2) //两个参数,第一个是字段,第二个是值
371 {372 list($field, $value) = func_get_args();373 self::$data['sql'] = "INSERT INTO ".self::$data['name']."({$field}) VALUES({$value})";374 $query = self::query();375 }376 elseif(func_num_args() === 1) //一个参数,数组
377 {378 list($data) = func_get_args();379 $field = '';380 $value = '';381 if (is_array($data))382 {383 foreach ($data as $key => $val)384 {385 $field .= "{$key},";386 if (is_string($val))387 {388 $value .= "'{$val}',";389 }390 else
391 {392 $value .= "{$val},";393 }394 }395 $field = rtrim($field, ',');396 $value = rtrim($value, ',');397 self::$data['sql'] = "INSERT INTO ".self::$data['name']."({$field}) VALUES ({$value})";398 $query = self::query();399 }400 }401
402 if (is_bool($query))403 {404 self::free($query);405 return self::rowNum(); //返回0表示没有行数影响,执行时成功的,返回>0的数字表示影响行数
406 }407 else
408 {409 self::setError(); //设置错误信息
410 return false;411 }412 }413
414 /**415 * 获取记录数416 * @param string $aliax 别名417 */
418 public function count($alias = 'num')419 {420 self::$data['sql'] = "SELECT COUNT(*) AS {$alias} FROM ".self::$data['name'].self::$data['where'];421 $query = self::query();422
423 $result = mysqli_fetch_array($query, self::$config['returntype']);424
425 self::free($query);426
427 return $result[$alias];428 }429
430 /**431 * 查询一条记录432 * @param string $id 主键字段的值433 * @return array $result 返回结果数组434 */
435 public function find($id = '')436 {437 if (empty($id))438 {439 self::$data['sql'] = "SELECT ".self::$data['field']." FROM `".self::$data['name']."`".self::$data['where'].self::$data['order']; //sql语句
440 }441 else
442 {443 self::$data['sql'] = "SELECT ".self::$data['field']." FROM `".self::$data['name']."` WHERE `".self::$config['pk']."`={$id}".self::$data['order'];444 }445 echo self::$data['sql'];446 $query = self::query();447
448 if (!is_bool($query))449 {450 $result = mysqli_fetch_array($query, self::$config['returntype']);451
452 self::free($query); //释放结果集
453
454 return $result; //返回结果
455 }456 else
457 {458 self::setError();459 return;460 }461 }462
463 /**464 * 查询记录465 * @param string $sql 查询的sql语句466 */
467 public function select($sql = '')468 {469 if (!empty($sql))470 {471 $query = self::query($sql);472 }473 else
474 {475 self::$data['sql'] = "SELECT ".self::$data['field']." FROM `".self::$data['name']."` ".self::$data['join'].self::$data['on'].self::$data['where'].self::$data['group'].self::$data['order'].self::$data['limit'];476 $query = self::query();477 }478 if (!is_bool($query))479 {480 $result = mysqli_fetch_all($query, self::$config['returntype']);481
482 self::free($query);483
484 return $result;485 }486 else
487 {488 self::setError();489 return;490 }491 }492
493 /**494 * 返回错误信息495 */
496 public functiongetError()497 {498 return self::$error;499 }500
501 /**502 * 获取当前数据库服务器版本503 */
504 public functiongetVersion()505 {506 if (self::$con)507 {508 return mysqli_get_server_info(self::$con);509 }510 }511
512 /**513 * 关闭数据库连接514 */
515 public function__destruct()516 {517 if (self::$con)518 {519 mysqli_close(self::$con);520 }521 }522
523 /**524 * 调用不存在的公共方法是触发525 */
526 public function __call($name, $arguments)527 {528 exit("在Core\\Db中不存在{$name}方法!");529 }530
531 /**532 * 当调用不存在的静态方法是触发533 */
534 static public function __callStatic($name, $params)535 {536 call_user_func_array(['self', 'init'], $params);537 }538 }