mysqli.php 19 KB

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