mysqli.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. <?php
  2. /**
  3. * mysqli驱动
  4. *
  5. *
  6. * @package
  7. */
  8. defined('InShopNC') or exit('Access Invalid!');
  9. require_once(BASE_CORE_PATH . '/framework/function/statistic_tm.php');
  10. class Db
  11. {
  12. private static $link = array();
  13. private static $iftransacte = true;
  14. const reconnect_time = 3600;
  15. private function __construct()
  16. {
  17. if (!extension_loaded('mysqli')) {
  18. throw_exception("Db Error: mysqli is not install");
  19. }
  20. }
  21. private static function connect($host = 'slave')
  22. {
  23. static $connect_time = 0;
  24. if((time() - $connect_time > self::reconnect_time) && $connect_time > 0)
  25. {
  26. if(is_object(self::$link[$host]) && self::$link[$host]->ping()) {
  27. return;
  28. } else {
  29. self::closeLink('master');
  30. self::closeLink('slave');
  31. }
  32. }
  33. if (C('db.master') == C('db.slave'))
  34. {
  35. if (is_object(self::$link['slave'])){
  36. self::$link['master'] = &self::$link['slave'];
  37. return ;
  38. }
  39. elseif(is_object(self::$link['master'])){
  40. self::$link['slave'] = &self::$link['master'];
  41. return ;
  42. }
  43. }
  44. if (!in_array($host,array('master','slave'))) {
  45. $host = 'slave';
  46. }
  47. if (is_object(self::$link[$host])) {
  48. return;
  49. }
  50. $conf = C('db.'.$host);
  51. self::$link[$host] = @new mysqli($conf['dbhost'], $conf['dbuser'], $conf['dbpwd'], $conf['dbname'], $conf['dbport']);
  52. if (mysqli_connect_errno()) {
  53. $err_no = mysqli_connect_errno();
  54. $error = mysqli_connect_error();
  55. throw_exception("Db Error: database connect failed errno={$err_no} err={$error}");
  56. }
  57. $connect_time = time();
  58. switch (strtoupper($conf['dbcharset']))
  59. {
  60. case 'UTF-8':
  61. $query_string = "
  62. SET CHARACTER_SET_CLIENT = utf8,
  63. CHARACTER_SET_CONNECTION = utf8,
  64. CHARACTER_SET_DATABASE = utf8,
  65. CHARACTER_SET_RESULTS = utf8,
  66. CHARACTER_SET_SERVER = utf8,
  67. COLLATION_CONNECTION = utf8_general_ci,
  68. COLLATION_DATABASE = utf8_general_ci,
  69. COLLATION_SERVER = utf8_general_ci,
  70. sql_mode=''";
  71. break;
  72. case 'GBK':
  73. $query_string = "
  74. SET CHARACTER_SET_CLIENT = gbk,
  75. CHARACTER_SET_CONNECTION = gbk,
  76. CHARACTER_SET_DATABASE = gbk,
  77. CHARACTER_SET_RESULTS = gbk,
  78. CHARACTER_SET_SERVER = gbk,
  79. COLLATION_CONNECTION = gbk_chinese_ci,
  80. COLLATION_DATABASE = gbk_chinese_ci,
  81. COLLATION_SERVER = gbk_chinese_ci,
  82. sql_mode=''";
  83. break;
  84. default:
  85. $error = "Db Error: charset is Invalid";
  86. throw_exception($error);
  87. }
  88. //进行编码声明
  89. if (!self::$link[$host]->query($query_string)) {
  90. throw_exception("Db Error: ".mysqli_error(self::$link[$host]));
  91. }
  92. }
  93. private static function closeLink($host)
  94. {
  95. if(is_object(self::$link[$host])){
  96. self::$link[$host]->close();
  97. }
  98. self::$link[$host] = null;
  99. }
  100. public static function ping($host = 'master') {
  101. if (is_object(self::$link[$host])) {
  102. self::$link[$host]->close();
  103. self::$link[$host] = null;
  104. }
  105. }
  106. /**
  107. * 执行查询
  108. *
  109. * @param string $sql
  110. * @return mixed
  111. */
  112. public static function query($sql, $host = 'master')
  113. {
  114. self::connect($host);
  115. $staer = new statistic_tm();
  116. $query = self::$link[$host]->query($sql);
  117. $staer->end();
  118. if ($query === false)
  119. {
  120. $error = 'Db Error: '.mysqli_error(self::$link[$host]);
  121. if (C('debug')) {
  122. throw_exception($error.'<br/>'.$sql);
  123. } else {
  124. Log::record($error."\r\n".$sql,Log::ERR);
  125. Log::record($sql,Log::SQL);
  126. return false;
  127. }
  128. }
  129. else
  130. {
  131. Log::record($sql . " [ RunTime:" . $staer->elapsed(6) . "s ]", Log::SQL);
  132. return $query;
  133. }
  134. }
  135. /**
  136. * 取得数组
  137. *
  138. * @param string $sql
  139. * @return bool/null/array
  140. */
  141. public static function getAll($sql, $host = 'slave')
  142. {
  143. self::connect($host);
  144. $result = self::query($sql, $host);
  145. if ($result === false) return array();
  146. $array = array();
  147. while ($tmp=mysqli_fetch_array($result,MYSQLI_ASSOC)){
  148. $array[] = $tmp;
  149. }
  150. return !empty($array) ? $array : null;
  151. }
  152. /**
  153. * SELECT查询
  154. *
  155. * @param array $param 参数
  156. * @param object $obj_page 分类对象
  157. * @return array
  158. */
  159. public static function select($param, $obj_page='', $host = 'slave'){
  160. self::connect($host);
  161. static $_cache = array();
  162. if (empty($param)) throw_exception('Db Error: select param is empty!');
  163. if (empty($param['field'])){
  164. $param['field'] = '*';
  165. }
  166. if (empty($param['count'])){
  167. $param['count'] = 'count(*)';
  168. }
  169. if (isset($param['index'])){
  170. $param['index'] = 'USE INDEX ('.$param['index'].')';
  171. }
  172. if (trim($param['where']) != ''){
  173. if (strtoupper(substr(trim($param['where']),0,5)) != 'WHERE'){
  174. if (strtoupper(substr(trim($param['where']),0,3)) == 'AND'){
  175. $param['where'] = substr(trim($param['where']),3);
  176. }
  177. $param['where'] = 'WHERE '.$param['where'];
  178. }
  179. }else {
  180. $param['where'] = '';
  181. }
  182. $param['where_group'] = '';
  183. if (!empty($param['group'])){
  184. $param['where_group'] .= ' group by '.$param['group'];
  185. }
  186. $param['where_order'] = '';
  187. if (!empty($param['order'])){
  188. $param['where_order'] .= ' order by '.$param['order'];
  189. }
  190. //判断是否是联表
  191. $tmp_table = explode(',',$param['table']);
  192. if (!empty($tmp_table) && count($tmp_table) > 1){
  193. //判断join表数量和join条件是否一致
  194. if ((count($tmp_table)-1) != count($param['join_on'])){
  195. throw_exception('Db Error: join number is wrong!');
  196. }
  197. //trim 掉空白字符
  198. foreach($tmp_table as $key=>$val){
  199. $tmp_table[$key] = trim($val) ;
  200. }
  201. //拼join on 语句
  202. $tmp_sql = '';
  203. for ($i=1;$i<count($tmp_table);$i++){
  204. $tmp_sql .= $param['join_type'].' `'.DBPRE.$tmp_table[$i].'` as `'.$tmp_table[$i].'` ON '.$param['join_on'][$i-1].' ';
  205. }
  206. $sql = 'SELECT '.$param['field'].' FROM `'.DBPRE.$tmp_table[0].'` as `'.$tmp_table[0].'` '.$tmp_sql.' '.$param['where'].$param['where_group'].$param['where_order'];
  207. //如果有分页,那么计算信息总数
  208. $count_sql = 'SELECT '.$param['count'].' as count FROM `'.DBPRE.$tmp_table[0].'` as `'.$tmp_table[0].'` '.$tmp_sql.' '.$param['where'].$param['where_group'];
  209. }else {
  210. $sql = 'SELECT '.$param['field'].' FROM `'.DBPRE.$param['table'].'` as `'.$param['table'].'` '.$param['index'].' '.$param['where'].$param['where_group'].$param['where_order'];
  211. $count_sql = 'SELECT '.$param['count'].' as count FROM `'.DBPRE.$param['table'].'` as `'.$param['table'].'` '.$param['index'].' '.$param['where'];
  212. }
  213. //limit ,如果有分页对象的话,那么优先分页对象
  214. if ($obj_page instanceof Page ){
  215. $count_query = self::query($count_sql,$host);
  216. $count_fetch = mysqli_fetch_array($count_query,MYSQLI_ASSOC);
  217. $obj_page->setTotalNum($count_fetch['count']);
  218. $param['limit'] = $obj_page->getLimitStart().",".$obj_page->getEachNum();
  219. }
  220. if ($param['limit'] != ''){
  221. $sql .= ' limit '.$param['limit'];
  222. }
  223. if ($param['cache'] !== false){
  224. $key = is_string($param['cache_key'])?$param['cache_key']:md5($sql);
  225. if (isset($_cache[$key])) return $_cache[$key];
  226. }
  227. $result = self::query($sql,$host);
  228. if ($result === false) $result = array();
  229. while ($tmp=mysqli_fetch_array($result,MYSQLI_ASSOC)){
  230. $array[] = $tmp;
  231. }
  232. if ($param['cache'] !== false && !isset($_cache[$key])){
  233. $_cache[$key] = $array;
  234. }
  235. return $array;
  236. }
  237. /**
  238. * 插入操作
  239. *
  240. * @param string $table_name 表名
  241. * @param array $insert_array 待插入数据
  242. * @return mixed
  243. */
  244. public static function insert($table_name, $insert_array=array(), $host = 'master'){
  245. self::connect($host);
  246. if (!is_array($insert_array)) return false;
  247. $fields = array();
  248. $value = array();
  249. foreach ($insert_array as $key => $val){
  250. $fields[] = self::parseKey($key);
  251. $value[] = self::parseValue($val);
  252. }
  253. $sql = 'INSERT INTO `'.DBPRE.$table_name.'` ('.implode(',',$fields).') VALUES('.implode(',',$value).')';
  254. //当数据库没有自增ID的情况下,返回 是否成功
  255. $result = self::query($sql, $host);
  256. $insert_id = self::getLastId($host);
  257. return $insert_id ? $insert_id : $result;
  258. }
  259. /**
  260. * 批量插入
  261. *
  262. * @param string $table_name 表名
  263. * @param array $insert_array 待插入数据
  264. * @return mixed
  265. */
  266. public static function insertAll($table_name, $insert_array=array(), $host = 'master')
  267. {
  268. self::connect($host);
  269. if (!is_array($insert_array[0])) return false;
  270. $fields = array_keys($insert_array[0]);
  271. array_walk($fields,array(self,'parseKey'));
  272. $values = array();
  273. foreach ($insert_array as $data) {
  274. $value = array();
  275. foreach ($data as $key=>$val) {
  276. $val = self::parseValue($val);
  277. if (is_scalar($val)){
  278. $value[] = $val;
  279. }
  280. }
  281. $values[] = '('.implode(',',$value).')';
  282. }
  283. $sql = 'INSERT INTO `'.DBPRE.$table_name.'` ('.implode(',',$fields).') VALUES '.implode(',',$values);
  284. $result = self::query($sql,$host);
  285. $insert_id = self::getLastId($host);
  286. return $insert_id ? $insert_id : $result;
  287. }
  288. /**
  289. * 更新操作
  290. *
  291. * @param string $table_name 表名
  292. * @param array $update_array 待更新数据
  293. * @param string $where 执行条件
  294. * @return bool
  295. */
  296. public static function update($table_name, $update_array = array(), $where = '', $host = 'master')
  297. {
  298. self::connect($host);
  299. if (!is_array($update_array)) return false;
  300. $string_value = '';
  301. foreach ($update_array as $k => $v){
  302. if (is_array($v)){
  303. switch ($v['sign']){
  304. case 'increase': $string_value .= " $k = $k + ". $v['value'] .","; break;
  305. case 'decrease': $string_value .= " $k = $k - ". $v['value'] .","; break;
  306. case 'calc': $string_value .= " $k = ". $v['value'] .","; break;
  307. default: $string_value .= " $k = ". self::parseValue($v['value']) .",";
  308. }
  309. }else {
  310. $string_value .= " $k = ". self::parseValue($v) .",";
  311. }
  312. }
  313. $string_value = trim(trim($string_value),',');
  314. if (trim($where) != ''){
  315. if (strtoupper(substr(trim($where),0,5)) != 'WHERE'){
  316. if (strtoupper(substr(trim($where),0,3)) == 'AND'){
  317. $where = substr(trim($where),3);
  318. }
  319. $where = ' WHERE '.$where;
  320. }
  321. }
  322. $sql = 'UPDATE `'.DBPRE.$table_name.'` AS `'.$table_name.'` SET '.$string_value.' '.$where;
  323. $result = self::query($sql, $host);
  324. return $result;
  325. }
  326. /**
  327. * 删除操作
  328. *
  329. * @param string $table_name 表名
  330. * @param string $where 执行条件
  331. * @return bool
  332. */
  333. public static function delete($table_name, $where = '', $host = 'master')
  334. {
  335. self::connect($host);
  336. if (trim($where) != ''){
  337. if (strtoupper(substr(trim($where),0,5)) != 'WHERE'){
  338. if (strtoupper(substr(trim($where),0,3)) == 'AND'){
  339. $where = substr(trim($where),3);
  340. }
  341. $where = ' WHERE '.$where;
  342. }
  343. $sql = 'DELETE FROM `'.DBPRE.$table_name.'` '.$where;
  344. return self::query($sql, $host);
  345. }else {
  346. throw_exception('Db Error: the condition of delete is empty!');
  347. }
  348. }
  349. /**
  350. * 取得上一步插入产生的ID
  351. *
  352. * @return int
  353. */
  354. public static function getLastId($host = 'master'){
  355. self::connect($host);
  356. $id = mysqli_insert_id(self::$link[$host]);
  357. if (!$id){
  358. $result = self::query('SELECT last_insert_id() as id',$host);
  359. if ($result === false) return false;
  360. $id = mysqli_fetch_array($result,MYSQLI_ASSOC);
  361. $id = $id['id'];
  362. }
  363. return $id;
  364. }
  365. /**
  366. * 取得一行信息
  367. *
  368. * @param array $param
  369. * @param string $fields
  370. * @return array
  371. */
  372. public static function getRow($param, $fields = '*', $host = 'slave')
  373. {
  374. self::connect($host);
  375. $table = $param['table'];
  376. $wfield = $param['field'];
  377. $value = $param['value'];
  378. if (is_array($wfield)){
  379. $where = array();
  380. foreach ($wfield as $k => $v){
  381. $where[] = $v."='".$value[$k]."'";
  382. }
  383. $where = implode(' and ',$where);
  384. }else {
  385. $where = $wfield."='".$value."'";
  386. }
  387. $sql = "SELECT ".$fields." FROM `".DBPRE.$table."` WHERE ".$where;
  388. $result = self::query($sql,$host);
  389. if ($result === false) return array();
  390. return mysqli_fetch_array($result,MYSQLI_ASSOC);
  391. }
  392. /**
  393. * 执行REPLACE操作
  394. *
  395. * @param string $table_name 表名
  396. * @param array $replace_array 待更新的数据
  397. * @return bool
  398. */
  399. public static function replace($table_name, $replace_array = array(), $host = 'master')
  400. {
  401. self::connect($host);
  402. if (!empty($replace_array))
  403. {
  404. $string_field = '';
  405. $string_value = '';
  406. foreach ($replace_array as $k => $v){
  407. $string_field .= " $k ,";
  408. $string_value .= " '". $v ."',";
  409. }
  410. $sql = 'REPLACE INTO `'.DBPRE.$table_name.'` ('.trim($string_field,', ').') VALUES('.trim($string_value,', ').')';
  411. return self::query($sql,$host);
  412. }else {
  413. return false;
  414. }
  415. }
  416. /**
  417. * 返回单表查询记录数量
  418. *
  419. * @param string $table 表名
  420. * @param $condition mixed 查询条件,可以为空,也可以为数组或字符串
  421. * @return int
  422. */
  423. public static function getCount($table, $condition = null, $host = 'slave')
  424. {
  425. self::connect($host);
  426. if (!empty($condition) && is_array($condition)){
  427. $where = '';
  428. foreach ($condition as $key=>$val) {
  429. self::parseKey($key);
  430. $val = self::parseValue($val);
  431. $where .= ' AND '.$key.'='.$val;
  432. }
  433. $where = ' WHERE '.substr($where,4);
  434. }elseif(is_string($condition)){
  435. if (strtoupper(substr(trim($condition),0,3)) == 'AND'){
  436. $where = ' WHERE '.substr(trim($condition),4);
  437. }else{
  438. $where = ' WHERE '.$condition;
  439. }
  440. }
  441. $sql = 'SELECT COUNT(*) as `count` FROM `'.DBPRE.$table.'` as `'.$table.'` '.(isset($where) ? $where : '');
  442. $result = self::query($sql,$host);
  443. if ($result === false) return 0;
  444. $result = mysqli_fetch_array($result,MYSQLI_ASSOC);
  445. return $result['count'];
  446. }
  447. /**
  448. * 执行SQL语句
  449. *
  450. * @param string $sql 待执行的SQL
  451. * @return
  452. */
  453. public static function execute($sql, $host = 'master'){
  454. self::connect($host);
  455. $result = self::query($sql,$host);
  456. return $result;
  457. }
  458. /**
  459. * 列出所有表
  460. *
  461. * @return array
  462. */
  463. public static function showTables($host = 'slave'){
  464. self::connect($host);
  465. $sql = 'SHOW TABLES';
  466. $result = self::query($sql,$host);
  467. if ($result === false) return array();
  468. $array = array();
  469. while ($tmp=mysqli_fetch_array($result,MYSQLI_ASSOC)){
  470. $array[] = $tmp;
  471. }
  472. return $array;
  473. }
  474. /**
  475. * 显示建表语句
  476. *
  477. * @param string $table
  478. * @return string
  479. */
  480. public static function showCreateTable($table, $host = 'slave'){
  481. self::connect($host);
  482. $sql = 'SHOW CREATE TABLE `'.DBPRE.$table.'`';
  483. $result = self::query($sql,$host);
  484. if ($result === false) return '';
  485. $result = mysqli_fetch_array($result,MYSQLI_ASSOC);
  486. return $result['Create Table'];
  487. }
  488. /**
  489. * 显示表结构信息
  490. *
  491. * @param string $table
  492. * @return array
  493. */
  494. public static function showColumns($table, $host = 'slave'){
  495. self::connect($host);
  496. $sql = 'SHOW COLUMNS FROM `'.DBPRE.$table.'`';
  497. $result = self::query($sql,$host);
  498. if ($result === false) return array();
  499. $array = array();
  500. while ($tmp=mysqli_fetch_array($result,MYSQLI_ASSOC)){
  501. $array[$tmp['Field']] = array(
  502. 'name' => $tmp['Field'],
  503. 'type' => $tmp['Type'],
  504. 'null' => $tmp['Null'],
  505. 'default' => $tmp['Default'],
  506. 'primary' => (strtolower($tmp['Key']) == 'pri'),
  507. 'autoinc' => (strtolower($tmp['Extra']) == 'auto_increment'),
  508. );
  509. }
  510. return $array;
  511. }
  512. /**
  513. * 取得服务器信息
  514. *
  515. * @return string
  516. */
  517. public static function getServerInfo($host = 'slave'){
  518. self::connect($host);
  519. $result = mysqli_get_server_info(self::$link[$host]);
  520. return $result;
  521. }
  522. /**
  523. * 格式化字段
  524. *
  525. * @param string $key 字段名
  526. * @return string
  527. */
  528. public static function parseKey(&$key){
  529. $key = trim($key);
  530. if(!preg_match('/[,\'\"\*\(\)`.\s]/',$key)) {
  531. $key = '`'.$key.'`';
  532. }
  533. return $key;
  534. }
  535. /**
  536. * 格式化值
  537. *
  538. * @param mixed $value
  539. * @return mixed
  540. */
  541. public static function parseValue($value){
  542. $value = addslashes(stripslashes($value));//重新加斜线,防止从数据库直接读取出错
  543. return "'".$value."'";
  544. }
  545. public static function beginTransaction($host = 'master')
  546. {
  547. self::connect($host);
  548. if (self::$iftransacte){
  549. self::$link[$host]->autocommit(false);//关闭自动提交
  550. }
  551. self::$iftransacte = false;
  552. }
  553. // public static function start_transaction($host = 'master')
  554. // {
  555. // self::connect($host);
  556. // if (self::$iftransacte){
  557. // self::$link[$host]->autocommit(false);//关闭自动提交
  558. // self::$iftransacte = false;
  559. // self::$link[$host]->begin_transaction(MYSQLI_TRANS_START_READ_ONLY);
  560. // }
  561. // }
  562. public static function commit($host = 'master')
  563. {
  564. if (!self::$iftransacte){
  565. $result = self::$link[$host]->commit();
  566. self::$link[$host]->autocommit(true);//开启自动提交
  567. self::$iftransacte = true;
  568. if (!$result) throw_exception("Db Error: ".mysqli_error(self::$link[$host]));
  569. }
  570. }
  571. public static function rollback($host = 'master')
  572. {
  573. if (!self::$iftransacte){
  574. $result = self::$link[$host]->rollback();
  575. self::$link[$host]->autocommit(true);
  576. self::$iftransacte = true;
  577. if (!$result) throw_exception("Db Error: ".mysqli_error(self::$link[$host]));
  578. }
  579. }
  580. public static function affected_rows($host = 'master')
  581. {
  582. return self::$link[$host]->affected_rows;
  583. }
  584. }