mysqli.php 17 KB

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