mysqli.php 19 KB

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