mysqli.php 17 KB

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