mysqli.php 17 KB

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