mysqli.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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 = 1800;
  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();
  26. }
  27. if (C('db.master') == C('db.slave'))
  28. {
  29. if (is_object(self::$link['slave'])){
  30. self::$link['master'] = & self::$link['slave'];
  31. return ;
  32. }elseif (is_object(self::$link['master'])){
  33. self::$link['slave'] = & self::$link['master'];
  34. return ;
  35. }
  36. }
  37. if (!in_array($host,array('master','slave'))) $host = 'slave';
  38. $conf = C('db.'.$host);
  39. if (is_object(self::$link[$host])) {
  40. return;
  41. }
  42. self::$link[$host] = @new mysqli($conf['dbhost'], $conf['dbuser'], $conf['dbpwd'], $conf['dbname'], $conf['dbport']);
  43. self::$connect_time = time();
  44. if (mysqli_connect_errno()) throw_exception("Db Error: database connect failed");
  45. switch (strtoupper($conf['dbcharset']))
  46. {
  47. case 'UTF-8':
  48. $query_string = "
  49. SET CHARACTER_SET_CLIENT = utf8,
  50. CHARACTER_SET_CONNECTION = utf8,
  51. CHARACTER_SET_DATABASE = utf8,
  52. CHARACTER_SET_RESULTS = utf8,
  53. CHARACTER_SET_SERVER = utf8,
  54. COLLATION_CONNECTION = utf8_general_ci,
  55. COLLATION_DATABASE = utf8_general_ci,
  56. COLLATION_SERVER = utf8_general_ci,
  57. sql_mode=''";
  58. break;
  59. case 'GBK':
  60. $query_string = "
  61. SET CHARACTER_SET_CLIENT = gbk,
  62. CHARACTER_SET_CONNECTION = gbk,
  63. CHARACTER_SET_DATABASE = gbk,
  64. CHARACTER_SET_RESULTS = gbk,
  65. CHARACTER_SET_SERVER = gbk,
  66. COLLATION_CONNECTION = gbk_chinese_ci,
  67. COLLATION_DATABASE = gbk_chinese_ci,
  68. COLLATION_SERVER = gbk_chinese_ci,
  69. sql_mode=''";
  70. break;
  71. default:
  72. $error = "Db Error: charset is Invalid";
  73. throw_exception($error);
  74. }
  75. //进行编码声明
  76. if (!self::$link[$host]->query($query_string)) {
  77. throw_exception("Db Error: ".mysqli_error(self::$link[$host]));
  78. }
  79. }
  80. private static function closeLink()
  81. {
  82. foreach(self::$link as $key => $db){
  83. if(is_object($db)){
  84. mysqli_close($db);
  85. }
  86. unset(self::$link[$key]);
  87. }
  88. }
  89. public static function ping($host = 'master') {
  90. if (is_object(self::$link[$host])) {
  91. // if (is_object(self::$link[$host]) && !self::$link[$host]->ping()) {
  92. self::$link[$host]->close();
  93. self::$link[$host] = null;
  94. }
  95. }
  96. /**
  97. * 执行查询
  98. *
  99. * @param string $sql
  100. * @return mixed
  101. */
  102. public static function query($sql, $host = 'master')
  103. {
  104. self::connect($host);
  105. $staer = new statistic_tm();
  106. $query = self::$link[$host]->query($sql);
  107. $staer->end();
  108. if ($query === false)
  109. {
  110. $error = 'Db Error: '.mysqli_error(self::$link[$host]);
  111. if (C('debug')) {
  112. throw_exception($error.'<br/>'.$sql);
  113. } else {
  114. Log::record($error."\r\n".$sql,Log::ERR);
  115. Log::record($sql,Log::SQL);
  116. return false;
  117. }
  118. }
  119. else
  120. {
  121. Log::record($sql . " [ RunTime:" . $staer->elapsed(6) . "s ]", Log::SQL);
  122. return $query;
  123. }
  124. }
  125. /**
  126. * 取得数组
  127. *
  128. * @param string $sql
  129. * @return bool/null/array
  130. */
  131. public static function getAll($sql, $host = 'slave'){
  132. self::connect($host);
  133. $result = self::query($sql, $host);
  134. if ($result === false) return array();
  135. $array = array();
  136. while ($tmp=mysqli_fetch_array($result,MYSQLI_ASSOC)){
  137. $array[] = $tmp;
  138. }
  139. //$array = mysqli_fetch_all($result,MYSQLI_ASSOC);
  140. return !empty($array) ? $array : null;
  141. }
  142. /**
  143. * SELECT查询
  144. *
  145. * @param array $param 参数
  146. * @param object $obj_page 分类对象
  147. * @return array
  148. */
  149. public static function select($param, $obj_page='', $host = 'slave'){
  150. self::connect($host);
  151. static $_cache = array();
  152. if (empty($param)) throw_exception('Db Error: select param is empty!');
  153. if (empty($param['field'])){
  154. $param['field'] = '*';
  155. }
  156. if (empty($param['count'])){
  157. $param['count'] = 'count(*)';
  158. }
  159. if (isset($param['index'])){
  160. $param['index'] = 'USE INDEX ('.$param['index'].')';
  161. }
  162. if (trim($param['where']) != ''){
  163. if (strtoupper(substr(trim($param['where']),0,5)) != 'WHERE'){
  164. if (strtoupper(substr(trim($param['where']),0,3)) == 'AND'){
  165. $param['where'] = substr(trim($param['where']),3);
  166. }
  167. $param['where'] = 'WHERE '.$param['where'];
  168. }
  169. }else {
  170. $param['where'] = '';
  171. }
  172. $param['where_group'] = '';
  173. if (!empty($param['group'])){
  174. $param['where_group'] .= ' group by '.$param['group'];
  175. }
  176. $param['where_order'] = '';
  177. if (!empty($param['order'])){
  178. $param['where_order'] .= ' order by '.$param['order'];
  179. }
  180. //判断是否是联表
  181. $tmp_table = explode(',',$param['table']);
  182. if (!empty($tmp_table) && count($tmp_table) > 1){
  183. //判断join表数量和join条件是否一致
  184. if ((count($tmp_table)-1) != count($param['join_on'])){
  185. throw_exception('Db Error: join number is wrong!');
  186. }
  187. //trim 掉空白字符
  188. foreach($tmp_table as $key=>$val){
  189. $tmp_table[$key] = trim($val) ;
  190. }
  191. //拼join on 语句
  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. foreach ($replace_array as $k => $v){
  388. $string_field .= " $k ,";
  389. $string_value .= " '". $v ."',";
  390. }
  391. $sql = 'REPLACE INTO `'.DBPRE.$table_name.'` ('.trim($string_field,', ').') VALUES('.trim($string_value,', ').')';
  392. return self::query($sql,$host);
  393. }else {
  394. return false;
  395. }
  396. }
  397. /**
  398. * 返回单表查询记录数量
  399. *
  400. * @param string $table 表名
  401. * @param $condition mixed 查询条件,可以为空,也可以为数组或字符串
  402. * @return int
  403. */
  404. public static function getCount($table, $condition = null, $host = 'slave'){
  405. self::connect($host);
  406. if (!empty($condition) && is_array($condition)){
  407. $where = '';
  408. foreach ($condition as $key=>$val) {
  409. self::parseKey($key);
  410. $val = self::parseValue($val);
  411. $where .= ' AND '.$key.'='.$val;
  412. }
  413. $where = ' WHERE '.substr($where,4);
  414. }elseif(is_string($condition)){
  415. if (strtoupper(substr(trim($condition),0,3)) == 'AND'){
  416. $where = ' WHERE '.substr(trim($condition),4);
  417. }else{
  418. $where = ' WHERE '.$condition;
  419. }
  420. }
  421. $sql = 'SELECT COUNT(*) as `count` FROM `'.DBPRE.$table.'` as `'.$table.'` '.(isset($where) ? $where : '');
  422. $result = self::query($sql,$host);
  423. if ($result === false) return 0;
  424. $result = mysqli_fetch_array($result,MYSQLI_ASSOC);
  425. return $result['count'];
  426. }
  427. /**
  428. * 执行SQL语句
  429. *
  430. * @param string $sql 待执行的SQL
  431. * @return
  432. */
  433. public static function execute($sql, $host = 'master'){
  434. self::connect($host);
  435. $result = self::query($sql,$host);
  436. return $result;
  437. }
  438. /**
  439. * 列出所有表
  440. *
  441. * @return array
  442. */
  443. public static function showTables($host = 'slave'){
  444. self::connect($host);
  445. $sql = 'SHOW TABLES';
  446. $result = self::query($sql,$host);
  447. if ($result === false) return array();
  448. $array = array();
  449. while ($tmp=mysqli_fetch_array($result,MYSQLI_ASSOC)){
  450. $array[] = $tmp;
  451. }
  452. return $array;
  453. }
  454. /**
  455. * 显示建表语句
  456. *
  457. * @param string $table
  458. * @return string
  459. */
  460. public static function showCreateTable($table, $host = 'slave'){
  461. self::connect($host);
  462. $sql = 'SHOW CREATE TABLE `'.DBPRE.$table.'`';
  463. $result = self::query($sql,$host);
  464. if ($result === false) return '';
  465. $result = mysqli_fetch_array($result,MYSQLI_ASSOC);
  466. return $result['Create Table'];
  467. }
  468. /**
  469. * 显示表结构信息
  470. *
  471. * @param string $table
  472. * @return array
  473. */
  474. public static function showColumns($table, $host = 'slave'){
  475. self::connect($host);
  476. $sql = 'SHOW COLUMNS FROM `'.DBPRE.$table.'`';
  477. $result = self::query($sql,$host);
  478. if ($result === false) return array();
  479. $array = array();
  480. while ($tmp=mysqli_fetch_array($result,MYSQLI_ASSOC)){
  481. $array[$tmp['Field']] = array(
  482. 'name' => $tmp['Field'],
  483. 'type' => $tmp['Type'],
  484. 'null' => $tmp['Null'],
  485. 'default' => $tmp['Default'],
  486. 'primary' => (strtolower($tmp['Key']) == 'pri'),
  487. 'autoinc' => (strtolower($tmp['Extra']) == 'auto_increment'),
  488. );
  489. }
  490. return $array;
  491. }
  492. /**
  493. * 取得服务器信息
  494. *
  495. * @return string
  496. */
  497. public static function getServerInfo($host = 'slave'){
  498. self::connect($host);
  499. $result = mysqli_get_server_info(self::$link[$host]);
  500. return $result;
  501. }
  502. /**
  503. * 格式化字段
  504. *
  505. * @param string $key 字段名
  506. * @return string
  507. */
  508. public static function parseKey(&$key){
  509. $key = trim($key);
  510. if(!preg_match('/[,\'\"\*\(\)`.\s]/',$key)) {
  511. $key = '`'.$key.'`';
  512. }
  513. return $key;
  514. }
  515. /**
  516. * 格式化值
  517. *
  518. * @param mixed $value
  519. * @return mixed
  520. */
  521. public static function parseValue($value){
  522. $value = addslashes(stripslashes($value));//重新加斜线,防止从数据库直接读取出错
  523. return "'".$value."'";
  524. }
  525. public static function beginTransaction($host = 'master'){
  526. self::connect($host);
  527. if (self::$iftransacte){
  528. self::$link[$host]->autocommit(false);//关闭自动提交
  529. }
  530. self::$iftransacte = false;
  531. }
  532. public static function commit($host = 'master'){
  533. if (!self::$iftransacte){
  534. $result = self::$link[$host]->commit();
  535. self::$link[$host]->autocommit(true);//开启自动提交
  536. self::$iftransacte = true;
  537. if (!$result) throw_exception("Db Error: ".mysqli_error(self::$link[$host]));
  538. }
  539. }
  540. public static function rollback($host = 'master'){
  541. if (!self::$iftransacte){
  542. $result = self::$link[$host]->rollback();
  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. }