mysqli.php 18 KB

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