mysqli.php 17 KB

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