mysqli.php 17 KB

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