mysqli.php 17 KB

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