mysqli.php 18 KB

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