mysql.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. <?php
  2. /**
  3. * mysql驱动
  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 = 1005;
  15. private function __construct()
  16. {
  17. if (!function_exists ("mysql_connect")) {
  18. throw_exception('Db Error: mysql is not install');
  19. }
  20. }
  21. public static function closelink()
  22. {
  23. foreach(self::$link as $db){
  24. if(is_object($db)){
  25. mysql_close($db);
  26. }
  27. }
  28. }
  29. public static function connect($host = 'slave')
  30. {
  31. if((time() - self::$connect_time > self::reconnect_time) && defined('MOBILE_SERVER') && self::$connect_time > 0) {
  32. self::closeLink();
  33. }
  34. if (C('db.master') == C('db.slave'))
  35. {
  36. if (is_object(self::$link['slave'])) {
  37. self::$link['master'] = & self::$link['slave'];return ;
  38. } elseif (is_object(self::$link['master'])) {
  39. self::$link['slave'] = & self::$link['master'];return ;
  40. }
  41. }
  42. if (!in_array($host,array('master','slave'))) $host = 'slave';
  43. $conf = C('db.'.$host);
  44. if (is_object(self::$link[$host])) return;
  45. if (@self::$link[$host] = mysql_connect($conf['dbhost'].':'.$conf['dbport'], $conf['dbuser'], $conf['dbpwd']))
  46. {
  47. if (!@mysql_select_db($conf['dbname'],self::$link[$host])) {
  48. throw_exception("Db Error: ".mysql_error(self::$link[$host]));
  49. }
  50. switch (strtoupper($conf['dbcharset']))
  51. {
  52. case 'UTF-8':
  53. $query_string = "
  54. SET CHARACTER_SET_CLIENT = utf8,
  55. CHARACTER_SET_CONNECTION = utf8,
  56. CHARACTER_SET_DATABASE = utf8,
  57. CHARACTER_SET_RESULTS = utf8,
  58. CHARACTER_SET_SERVER = utf8,
  59. COLLATION_CONNECTION = utf8_general_ci,
  60. COLLATION_DATABASE = utf8_general_ci,
  61. COLLATION_SERVER = utf8_general_ci,
  62. sql_mode=''";
  63. break;
  64. case 'GBK':
  65. $query_string = "
  66. SET CHARACTER_SET_CLIENT = gbk,
  67. CHARACTER_SET_CONNECTION = gbk,
  68. CHARACTER_SET_DATABASE = gbk,
  69. CHARACTER_SET_RESULTS = gbk,
  70. CHARACTER_SET_SERVER = gbk,
  71. COLLATION_CONNECTION = gbk_chinese_ci,
  72. COLLATION_DATABASE = gbk_chinese_ci,
  73. COLLATION_SERVER = gbk_chinese_ci,
  74. sql_mode=''";
  75. break;
  76. default:
  77. throw_exception("Db Error: charset is Invalid");
  78. }
  79. if (!mysql_query($query_string)){
  80. throw_exception("Db Error: ".mysql_error(self::$link[$host]));
  81. }
  82. self::$connect_time = time();
  83. }
  84. else
  85. {
  86. throw_exception("Db Error: database connect failed");
  87. }
  88. }
  89. public static function ping($host = 'master') {
  90. if (is_object(self::$link[$host])) {
  91. mysql_close(self::$link[$host]);
  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 = mysql_query($sql,self::$link[$host]);
  106. if (C('debug')) addUpTime('queryEndTime');
  107. if ($query === false)
  108. {
  109. $error = "Db Error: ".mysql_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. return false;
  115. }
  116. } else {
  117. Log::record($sql." [ {$host} RunTime:".addUpTime("queryStartTime",'queryEndTime',6)."s ]",Log::SQL);
  118. return $query;
  119. }
  120. }
  121. /**
  122. * 取得查询操作
  123. *
  124. * @param string $sql
  125. * @return bool/null/array
  126. */
  127. public static function getAll($sql, $host = 'slave')
  128. {
  129. self::connect($host);
  130. $result = self::query($sql,$host);
  131. if ($result === false) return array();
  132. $array = array();
  133. while ($tmp=mysql_fetch_array($result,MYSQL_ASSOC)) {
  134. $array[] = $tmp;
  135. }
  136. return !empty($array) ? $array : null;
  137. }
  138. /**
  139. * 检索数据
  140. *
  141. * @param array $param 参数
  142. * @param object $obj_page 分类对象
  143. * @return array
  144. */
  145. public static function select($param, $obj_page = '', $host = 'slave')
  146. {
  147. self::connect($host);
  148. static $_cache = array();
  149. if (empty($param)){
  150. throw_exception('Db Error: select param is empty!');
  151. }
  152. if (empty($param['field'])){
  153. $param['field'] = '*';
  154. }
  155. if (empty($param['count'])){
  156. $param['count'] = 'count(*)';
  157. }
  158. if (isset($param['index'])){
  159. $param['index'] = 'USE INDEX ('.$param['index'].')';
  160. }
  161. if (trim($param['where']) != '')
  162. {
  163. if (strtoupper(substr(trim($param['where']),0,5)) != 'WHERE')
  164. {
  165. if (strtoupper(substr(trim($param['where']),0,3)) == 'AND'){
  166. $param['where'] = substr(trim($param['where']),3);
  167. }
  168. $param['where'] = 'WHERE '.$param['where'];
  169. }
  170. }
  171. $param['where_group'] = '';
  172. if (!empty($param['group'])) {
  173. $param['where_group'] .= ' group by '.$param['group'];
  174. }
  175. $param['where_order'] = '';
  176. if (!empty($param['order'])){
  177. $param['where_order'] .= ' order by '.$param['order'];
  178. }
  179. //判断是否是联表查询
  180. $tmp_table = explode(',',$param['table']);
  181. if (!empty($tmp_table) && count($tmp_table) > 1)
  182. {
  183. if ((count($tmp_table)-1) != count($param['join_on'])){
  184. throw_exception('Db Error: join number is wrong!');
  185. }
  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);
  203. $count_fetch = mysql_fetch_array($count_query,MYSQL_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=mysql_fetch_array($result,MYSQL_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. {
  233. self::connect($host);
  234. if (!is_array($insert_array)) return false;
  235. $fields = array();
  236. $value = array();
  237. foreach ($insert_array as $key => $val){
  238. $fields[] = self::parseKey($key);
  239. $value[] = self::parseValue($val);
  240. }
  241. $sql = 'INSERT INTO `'.DBPRE.$table_name.'` ('.implode(',',$fields).') VALUES('.implode(',',$value).')';
  242. //当数据库没有自增ID的情况下,返回 是否成功
  243. $result = self::query($sql,$host);
  244. $insert_id = self::getLastId();
  245. return $insert_id ? $insert_id : $result;
  246. }
  247. /**
  248. * 批量插入
  249. *
  250. * @param string $table_name 表名
  251. * @param array $insert_array 待插入数据
  252. * @return mixed
  253. */
  254. public static function insertAll($table_name, $insert_array = array(), $host = 'master')
  255. {
  256. self::connect('master');
  257. if (!is_array($insert_array[0])) return false;
  258. $fields = array_keys($insert_array[0]);
  259. array_walk($fields,array(self,'parseKey'));
  260. $values = array();
  261. foreach ($insert_array as $data)
  262. {
  263. $value = array();
  264. foreach ($data as $key=>$val) {
  265. $val = self::parseValue($val);
  266. if (is_scalar($val)){
  267. $value[] = $val;
  268. }
  269. }
  270. $values[] = '('.implode(',',$value).')';
  271. }
  272. $sql = 'INSERT INTO `'.DBPRE.$table_name.'` ('.implode(',',$fields).') VALUES '.implode(',',$values);
  273. $result = self::query($sql,$host);
  274. $insert_id = self::getLastId();
  275. return $insert_id ? $insert_id : $result;
  276. }
  277. /**
  278. * 更新操作
  279. *
  280. * @param string $table_name 表名
  281. * @param array $update_array 待更新数据
  282. * @param string $where 执行条件
  283. * @return bool
  284. */
  285. public static function update($table_name, $update_array = array(), $where = '', $host = 'master')
  286. {
  287. self::connect('master');
  288. if (!empty($update_array))
  289. {
  290. $string_value = '';
  291. foreach ($update_array as $k => $v)
  292. {
  293. if (is_array($v))
  294. {
  295. switch ($v['sign'])
  296. {
  297. case 'increase': $string_value .= " $k = $k + ". $v['value'] .","; break;
  298. case 'decrease': $string_value .= " $k = $k - ". $v['value'] .","; break;
  299. case 'calc': $string_value .= " $k = ". $v['value'] .","; break;
  300. default: $string_value .= " $k = ". self::parseValue($v['value']) .",";
  301. }
  302. }
  303. else
  304. {
  305. $string_value .= " $k = ". self::parseValue($v) .",";
  306. }
  307. }
  308. $string_value = trim($string_value,', ');
  309. if (trim($where) != '')
  310. {
  311. if (strtoupper(substr(trim($where),0,5)) != 'WHERE')
  312. {
  313. if (strtoupper(substr(trim($where),0,3)) == 'AND'){
  314. $where = substr(trim($where),3);
  315. }
  316. $where = ' WHERE '.$where;
  317. }
  318. }
  319. $sql = 'UPDATE `'.DBPRE.$table_name.'` AS `'.$table_name.'` SET '.$string_value.' '.$where;
  320. return self::query($sql,$host);
  321. } else {
  322. return false;
  323. }
  324. }
  325. /**
  326. * 删除
  327. *
  328. * @param string $table_name 表名
  329. * @param string $where 执行条件
  330. * @return bool
  331. */
  332. public static function delete($table_name, $where = '', $host = 'master')
  333. {
  334. self::connect($host);
  335. if (trim($where) != '')
  336. {
  337. if (strtoupper(substr(trim($where),0,5)) != 'WHERE')
  338. {
  339. if (strtoupper(substr(trim($where),0,3)) == 'AND') {
  340. $where = substr(trim($where),3);
  341. }
  342. $where = ' WHERE '.$where;
  343. }
  344. $sql = 'DELETE FROM `'.DBPRE.$table_name.'` '.$where;
  345. return self::query($sql,$host);
  346. } else {
  347. throw_exception("Db Error: the condition of delete is empty!");
  348. }
  349. }
  350. /**
  351. * 取取insert_id
  352. *
  353. * @return int
  354. */
  355. public static function getLastId($host = 'master')
  356. {
  357. self::commit($host);
  358. $id = mysql_insert_id(self::$link[$host]);
  359. if (!$id){
  360. $result = self::query('SELECT last_insert_id() as id',$host);
  361. if ($result === false) return false;
  362. $id = mysql_fetch_array($result,MYSQL_ASSOC);
  363. $id = $id['id'];
  364. }
  365. return $id;
  366. }
  367. /**
  368. * 取得一行信息
  369. *
  370. * @param array $param
  371. * @param string $fields
  372. * @return array
  373. */
  374. public static function getRow($param, $fields = '*', $host = 'master')
  375. {
  376. self::connect($host);
  377. $table = $param['table'];
  378. $wfield = $param['field'];
  379. $value = $param['value'];
  380. //判断字段是否是数组
  381. if (is_array($wfield))
  382. {
  383. $where = array();
  384. foreach ($wfield as $k => $v){
  385. $where[] = $v."='".$value[$k]."'";
  386. }
  387. $where = implode(' and ',$where);
  388. }
  389. else {
  390. $where = $wfield."='".$value."'";
  391. }
  392. $sql = "SELECT ".$fields." FROM `".DBPRE.$table."` WHERE ".$where;
  393. $result = self::query($sql,$host);
  394. if ($result === false) return array();
  395. return mysql_fetch_array($result,MYSQL_ASSOC);
  396. }
  397. /**
  398. * 执行REPLACE操作
  399. *
  400. * @param string $table_name 表名
  401. * @param array $replace_array 待更新的数据
  402. * @return bool
  403. */
  404. public static function replace($table_name, $replace_array = array(), $host = 'master')
  405. {
  406. self::connect($host);
  407. if (!empty($replace_array))
  408. {
  409. foreach ($replace_array as $k => $v){
  410. $string_field .= " $k ,";
  411. $string_value .= " '". $v ."',";
  412. }
  413. $sql = 'REPLACE INTO `'.DBPRE.$table_name.'` ('.trim($string_field,', ').') VALUES('.trim($string_value,', ').')';
  414. return self::query($sql,$host);
  415. } else {
  416. return false;
  417. }
  418. }
  419. /**
  420. * 返回单表查询记录数量
  421. *
  422. * @param string $table 表名
  423. * @param $condition mixed 查询条件,可以为空,也可以为数组或字符串
  424. * @return int
  425. */
  426. public static function getCount($table, $condition = null, $host = 'slave')
  427. {
  428. self::connect($host);
  429. if (!empty($condition) && is_array($condition))
  430. {
  431. $where = '';
  432. foreach ($condition as $key=>$val) {
  433. self::parseKey($key);
  434. $val = self::parseValue($val);
  435. $where .= ' AND '.$key.'='.$val;
  436. }
  437. $where = ' WHERE '.substr($where,4);
  438. }
  439. elseif(is_string($condition))
  440. {
  441. if (strtoupper(substr(trim($condition),0,3)) == 'AND'){
  442. $where = ' WHERE '.substr(trim($condition),4);
  443. }else{
  444. $where = ' WHERE '.$condition;
  445. }
  446. }
  447. $sql = 'SELECT COUNT(*) as `count` FROM `'.DBPRE.$table.'` as `'.$table.'` '.(isset($where) ? $where : '');
  448. $result = self::query($sql,$host);
  449. if ($result === false) return 0;
  450. $result = mysql_fetch_array($result,MYSQL_ASSOC);
  451. return $result['count'];
  452. }
  453. /**
  454. * 执行SQL语句
  455. *
  456. * @param string $sql
  457. * @return
  458. */
  459. public static function execute($sql, $host = 'master')
  460. {
  461. self::connect($host);
  462. return self::query($sql,$host);
  463. }
  464. /**
  465. * 列出所有表
  466. *
  467. * @return array
  468. */
  469. public static function showTables($host = 'slave')
  470. {
  471. self::connect($host);
  472. $sql = 'SHOW TABLES';
  473. $result = self::query($sql,$host);
  474. if ($result === false) return array();
  475. $array = array();
  476. while ($tmp=mysql_fetch_array($result,MYSQL_ASSOC)){
  477. $array[] = $tmp;
  478. }
  479. return $array;
  480. }
  481. /**
  482. * 显示建表语句
  483. *
  484. * @param string $table
  485. * @return string
  486. */
  487. public static function showCreateTable($table, $host = 'slave')
  488. {
  489. self::connect($host);
  490. $sql = 'SHOW CREATE TABLE `'.DBPRE.$table.'`';
  491. $result = self::query($sql,$host);
  492. if ($result === false) return '';
  493. $result = mysql_fetch_array($result,MYSQL_ASSOC);
  494. return $result['Create Table'];
  495. }
  496. /**
  497. * 显示表结构
  498. *
  499. * @param string $table
  500. * @return array
  501. */
  502. public static function showColumns($table, $host = 'slave')
  503. {
  504. self::connect($host);
  505. $sql = 'SHOW COLUMNS FROM `'.DBPRE.$table.'`';
  506. $result = self::query($sql,$host);
  507. if ($result === false) return array();
  508. $array = array();
  509. while ($tmp=mysql_fetch_array($result,MYSQL_ASSOC)){
  510. $array[$tmp['Field']] = array(
  511. 'name' => $tmp['Field'],
  512. 'type' => $tmp['Type'],
  513. 'null' => $tmp['Null'],
  514. 'default' => $tmp['Default'],
  515. 'primary' => (strtolower($tmp['Key']) == 'pri'),
  516. 'autoinc' => (strtolower($tmp['Extra']) == 'auto_increment'),
  517. );
  518. }
  519. return $array;
  520. }
  521. /**
  522. * 取得服务器信息
  523. *
  524. * @return string
  525. */
  526. public static function getServerInfo($host = 'slave'){
  527. self::connect($host);
  528. $result = mysql_get_server_info(self::$link[$host]);
  529. return $result;
  530. }
  531. /**
  532. * 格式化字段
  533. *
  534. * @param string $key 字段名
  535. * @return string
  536. */
  537. public static function parseKey(&$key){
  538. $key = trim($key);
  539. if(!preg_match('/[,\'\"\*\(\)`.\s]/',$key)) {
  540. $key = '`'.$key.'`';
  541. }
  542. return $key;
  543. }
  544. /**
  545. * 格式化值
  546. *
  547. * @param mixed $value
  548. * @return mixed
  549. */
  550. public static function parseValue($value){
  551. $value = addslashes(stripslashes($value));//重新加斜线,防止从数据库直接读取出错
  552. return "'".$value."'";
  553. }
  554. public static function beginTransaction($host = 'master'){
  555. self::connect($host);
  556. if (self::$iftransacte){
  557. mysql_query('START TRANSACTION',self::$link[$host]);
  558. self::$iftransacte = false;
  559. }
  560. }
  561. public static function commit($host = 'master'){
  562. if (!self::$iftransacte){
  563. $result = mysql_query('COMMIT',self::$link[$host]);
  564. self::$iftransacte = true;
  565. if (!$result) throw_exception("Db Error: ".mysql_error(self::$link[$host]));
  566. }
  567. }
  568. public static function rollback($host = 'master'){
  569. if (!self::$iftransacte){
  570. $result = mysql_query('ROLLBACK',self::$link[$host]);
  571. self::$iftransacte = true;
  572. if (!$result) throw_exception("Db Error: ".mysql_error(self::$link[$host]));
  573. }
  574. }
  575. public static function affected_rows($host = 'master') {
  576. self::connect($host);
  577. return mysql_affected_rows($host);
  578. }
  579. }