mysql.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. // if (is_object(self::$link[$host]) && !mysql_ping(self::$link[$host])) {
  92. mysql_close(self::$link[$host]);
  93. self::$link[$host] = null;
  94. }
  95. }
  96. /**
  97. * 执行查询
  98. *
  99. * @param string $sql
  100. * @return mixed
  101. */
  102. public static function query($sql, $host = 'master')
  103. {
  104. self::connect($host);
  105. if (C('debug')) addUpTime('queryStartTime');
  106. $query = mysql_query($sql,self::$link[$host]);
  107. if (C('debug')) addUpTime('queryEndTime');
  108. if ($query === false)
  109. {
  110. $error = "Db Error: ".mysql_error(self::$link[$host]);
  111. if (C('debug')) {
  112. throw_exception($error.'<br/>'.$sql);
  113. } else {
  114. Log::record($error."\r\n".$sql,Log::ERR);
  115. return false;
  116. }
  117. } else {
  118. Log::record($sql." [ RunTime:".addUpTime('queryStartTime','queryEndTime',6)."s ]",Log::SQL);
  119. return $query;
  120. }
  121. }
  122. /**
  123. * 取得查询操作
  124. *
  125. * @param string $sql
  126. * @return bool/null/array
  127. */
  128. public static function getAll($sql, $host = 'slave')
  129. {
  130. self::connect($host);
  131. $result = self::query($sql,$host);
  132. if ($result === false) return array();
  133. $array = array();
  134. while ($tmp=mysql_fetch_array($result,MYSQL_ASSOC)) {
  135. $array[] = $tmp;
  136. }
  137. return !empty($array) ? $array : null;
  138. }
  139. /**
  140. * 检索数据
  141. *
  142. * @param array $param 参数
  143. * @param object $obj_page 分类对象
  144. * @return array
  145. */
  146. public static function select($param, $obj_page = '', $host = 'slave')
  147. {
  148. self::connect($host);
  149. static $_cache = array();
  150. if (empty($param)){
  151. throw_exception('Db Error: select param is empty!');
  152. }
  153. if (empty($param['field'])){
  154. $param['field'] = '*';
  155. }
  156. if (empty($param['count'])){
  157. $param['count'] = 'count(*)';
  158. }
  159. if (isset($param['index'])){
  160. $param['index'] = 'USE INDEX ('.$param['index'].')';
  161. }
  162. if (trim($param['where']) != '')
  163. {
  164. if (strtoupper(substr(trim($param['where']),0,5)) != 'WHERE')
  165. {
  166. if (strtoupper(substr(trim($param['where']),0,3)) == 'AND'){
  167. $param['where'] = substr(trim($param['where']),3);
  168. }
  169. $param['where'] = 'WHERE '.$param['where'];
  170. }
  171. }
  172. $param['where_group'] = '';
  173. if (!empty($param['group'])) {
  174. $param['where_group'] .= ' group by '.$param['group'];
  175. }
  176. $param['where_order'] = '';
  177. if (!empty($param['order'])){
  178. $param['where_order'] .= ' order by '.$param['order'];
  179. }
  180. //判断是否是联表查询
  181. $tmp_table = explode(',',$param['table']);
  182. if (!empty($tmp_table) && count($tmp_table) > 1)
  183. {
  184. if ((count($tmp_table)-1) != count($param['join_on'])){
  185. throw_exception('Db Error: join number is wrong!');
  186. }
  187. foreach($tmp_table as $key=>$val){
  188. $tmp_table[$key] = trim($val) ;
  189. }
  190. //拼join on 语句
  191. for ($i=1;$i<count($tmp_table);$i++){
  192. $tmp_sql .= $param['join_type'].' `'.DBPRE.$tmp_table[$i].'` as `'.$tmp_table[$i].'` ON '.$param['join_on'][$i-1].' ';
  193. }
  194. $sql = 'SELECT '.$param['field'].' FROM `'.DBPRE.$tmp_table[0].'` as `'.$tmp_table[0].'` '.$tmp_sql.' '.$param['where'].$param['where_group'].$param['where_order'];
  195. //如果有分页,计算信息总数
  196. $count_sql = 'SELECT '.$param['count'].' as count FROM `'.DBPRE.$tmp_table[0].'` as `'.$tmp_table[0].'` '.$tmp_sql.' '.$param['where'].$param['where_group'];
  197. } else {
  198. $sql = 'SELECT '.$param['field'].' FROM `'.DBPRE.$param['table'].'` as `'.$param['table'].'` '.$param['index'].' '.$param['where'].$param['where_group'].$param['where_order'];
  199. $count_sql = 'SELECT '.$param['count'].' as count FROM `'.DBPRE.$param['table'].'` as `'.$param['table'].'` '.$param['index'].' '.$param['where'];
  200. }
  201. //limit ,如果有分页对象的话,那么优先分页对象
  202. if ($obj_page instanceof Page ) {
  203. $count_query = self::query($count_sql);
  204. $count_fetch = mysql_fetch_array($count_query,MYSQL_ASSOC);
  205. $obj_page->setTotalNum($count_fetch['count']);
  206. $param['limit'] = $obj_page->getLimitStart().",".$obj_page->getEachNum();
  207. }
  208. if ($param['limit'] != ''){
  209. $sql .= ' limit '.$param['limit'];
  210. }
  211. if ($param['cache'] !== false){
  212. $key = is_string($param['cache_key'])?$param['cache_key']:md5($sql);
  213. if (isset($_cache[$key])) return $_cache[$key];
  214. }
  215. $result = self::query($sql,$host);
  216. if ($result === false) $result = array();
  217. while ($tmp=mysql_fetch_array($result,MYSQL_ASSOC)){
  218. $array[] = $tmp;
  219. }
  220. if ($param['cache'] !== false && !isset($_cache[$key])){
  221. $_cache[$key] = $array;
  222. }
  223. return $array;
  224. }
  225. /**
  226. * 插入操作
  227. *
  228. * @param string $table_name 表名
  229. * @param array $insert_array 待插入数据
  230. * @return mixed
  231. */
  232. public static function insert($table_name, $insert_array = array(), $host = 'master')
  233. {
  234. self::connect($host);
  235. if (!is_array($insert_array)) return false;
  236. $fields = array();
  237. $value = array();
  238. foreach ($insert_array as $key => $val){
  239. $fields[] = self::parseKey($key);
  240. $value[] = self::parseValue($val);
  241. }
  242. $sql = 'INSERT INTO `'.DBPRE.$table_name.'` ('.implode(',',$fields).') VALUES('.implode(',',$value).')';
  243. //当数据库没有自增ID的情况下,返回 是否成功
  244. $result = self::query($sql,$host);
  245. $insert_id = self::getLastId();
  246. return $insert_id ? $insert_id : $result;
  247. }
  248. /**
  249. * 批量插入
  250. *
  251. * @param string $table_name 表名
  252. * @param array $insert_array 待插入数据
  253. * @return mixed
  254. */
  255. public static function insertAll($table_name, $insert_array = array(), $host = 'master')
  256. {
  257. self::connect('master');
  258. if (!is_array($insert_array[0])) return false;
  259. $fields = array_keys($insert_array[0]);
  260. array_walk($fields,array(self,'parseKey'));
  261. $values = array();
  262. foreach ($insert_array as $data)
  263. {
  264. $value = array();
  265. foreach ($data as $key=>$val) {
  266. $val = self::parseValue($val);
  267. if (is_scalar($val)){
  268. $value[] = $val;
  269. }
  270. }
  271. $values[] = '('.implode(',',$value).')';
  272. }
  273. $sql = 'INSERT INTO `'.DBPRE.$table_name.'` ('.implode(',',$fields).') VALUES '.implode(',',$values);
  274. $result = self::query($sql,$host);
  275. $insert_id = self::getLastId();
  276. return $insert_id ? $insert_id : $result;
  277. }
  278. /**
  279. * 更新操作
  280. *
  281. * @param string $table_name 表名
  282. * @param array $update_array 待更新数据
  283. * @param string $where 执行条件
  284. * @return bool
  285. */
  286. public static function update($table_name, $update_array = array(), $where = '', $host = 'master')
  287. {
  288. self::connect('master');
  289. if (!empty($update_array))
  290. {
  291. $string_value = '';
  292. foreach ($update_array as $k => $v)
  293. {
  294. if (is_array($v))
  295. {
  296. switch ($v['sign'])
  297. {
  298. case 'increase': $string_value .= " $k = $k + ". $v['value'] .","; break;
  299. case 'decrease': $string_value .= " $k = $k - ". $v['value'] .","; break;
  300. case 'calc': $string_value .= " $k = ". $v['value'] .","; break;
  301. default: $string_value .= " $k = ". self::parseValue($v['value']) .",";
  302. }
  303. }
  304. else
  305. {
  306. $string_value .= " $k = ". self::parseValue($v) .",";
  307. }
  308. }
  309. $string_value = trim($string_value,', ');
  310. if (trim($where) != '')
  311. {
  312. if (strtoupper(substr(trim($where),0,5)) != 'WHERE')
  313. {
  314. if (strtoupper(substr(trim($where),0,3)) == 'AND'){
  315. $where = substr(trim($where),3);
  316. }
  317. $where = ' WHERE '.$where;
  318. }
  319. }
  320. $sql = 'UPDATE `'.DBPRE.$table_name.'` AS `'.$table_name.'` SET '.$string_value.' '.$where;
  321. return self::query($sql,$host);
  322. } else {
  323. return false;
  324. }
  325. }
  326. /**
  327. * 删除
  328. *
  329. * @param string $table_name 表名
  330. * @param string $where 执行条件
  331. * @return bool
  332. */
  333. public static function delete($table_name, $where = '', $host = 'master')
  334. {
  335. self::connect($host);
  336. if (trim($where) != '')
  337. {
  338. if (strtoupper(substr(trim($where),0,5)) != 'WHERE')
  339. {
  340. if (strtoupper(substr(trim($where),0,3)) == 'AND') {
  341. $where = substr(trim($where),3);
  342. }
  343. $where = ' WHERE '.$where;
  344. }
  345. $sql = 'DELETE FROM `'.DBPRE.$table_name.'` '.$where;
  346. return self::query($sql,$host);
  347. } else {
  348. throw_exception("Db Error: the condition of delete is empty!");
  349. }
  350. }
  351. /**
  352. * 取取insert_id
  353. *
  354. * @return int
  355. */
  356. public static function getLastId($host = 'master')
  357. {
  358. self::commit($host);
  359. $id = mysql_insert_id(self::$link[$host]);
  360. if (!$id){
  361. $result = self::query('SELECT last_insert_id() as id',$host);
  362. if ($result === false) return false;
  363. $id = mysql_fetch_array($result,MYSQL_ASSOC);
  364. $id = $id['id'];
  365. }
  366. return $id;
  367. }
  368. /**
  369. * 取得一行信息
  370. *
  371. * @param array $param
  372. * @param string $fields
  373. * @return array
  374. */
  375. public static function getRow($param, $fields = '*', $host = 'master')
  376. {
  377. self::connect($host);
  378. $table = $param['table'];
  379. $wfield = $param['field'];
  380. $value = $param['value'];
  381. //判断字段是否是数组
  382. if (is_array($wfield))
  383. {
  384. $where = array();
  385. foreach ($wfield as $k => $v){
  386. $where[] = $v."='".$value[$k]."'";
  387. }
  388. $where = implode(' and ',$where);
  389. }
  390. else {
  391. $where = $wfield."='".$value."'";
  392. }
  393. $sql = "SELECT ".$fields." FROM `".DBPRE.$table."` WHERE ".$where;
  394. $result = self::query($sql,$host);
  395. if ($result === false) return array();
  396. return mysql_fetch_array($result,MYSQL_ASSOC);
  397. }
  398. /**
  399. * 执行REPLACE操作
  400. *
  401. * @param string $table_name 表名
  402. * @param array $replace_array 待更新的数据
  403. * @return bool
  404. */
  405. public static function replace($table_name, $replace_array = array(), $host = 'master')
  406. {
  407. self::connect($host);
  408. if (!empty($replace_array))
  409. {
  410. foreach ($replace_array as $k => $v){
  411. $string_field .= " $k ,";
  412. $string_value .= " '". $v ."',";
  413. }
  414. $sql = 'REPLACE INTO `'.DBPRE.$table_name.'` ('.trim($string_field,', ').') VALUES('.trim($string_value,', ').')';
  415. return self::query($sql,$host);
  416. } else {
  417. return false;
  418. }
  419. }
  420. /**
  421. * 返回单表查询记录数量
  422. *
  423. * @param string $table 表名
  424. * @param $condition mixed 查询条件,可以为空,也可以为数组或字符串
  425. * @return int
  426. */
  427. public static function getCount($table, $condition = null, $host = 'slave')
  428. {
  429. self::connect($host);
  430. if (!empty($condition) && is_array($condition))
  431. {
  432. $where = '';
  433. foreach ($condition as $key=>$val) {
  434. self::parseKey($key);
  435. $val = self::parseValue($val);
  436. $where .= ' AND '.$key.'='.$val;
  437. }
  438. $where = ' WHERE '.substr($where,4);
  439. }
  440. elseif(is_string($condition))
  441. {
  442. if (strtoupper(substr(trim($condition),0,3)) == 'AND'){
  443. $where = ' WHERE '.substr(trim($condition),4);
  444. }else{
  445. $where = ' WHERE '.$condition;
  446. }
  447. }
  448. $sql = 'SELECT COUNT(*) as `count` FROM `'.DBPRE.$table.'` as `'.$table.'` '.(isset($where) ? $where : '');
  449. $result = self::query($sql,$host);
  450. if ($result === false) return 0;
  451. $result = mysql_fetch_array($result,MYSQL_ASSOC);
  452. return $result['count'];
  453. }
  454. /**
  455. * 执行SQL语句
  456. *
  457. * @param string $sql
  458. * @return
  459. */
  460. public static function execute($sql, $host = 'master')
  461. {
  462. self::connect($host);
  463. return self::query($sql,$host);
  464. }
  465. /**
  466. * 列出所有表
  467. *
  468. * @return array
  469. */
  470. public static function showTables($host = 'slave')
  471. {
  472. self::connect($host);
  473. $sql = 'SHOW TABLES';
  474. $result = self::query($sql,$host);
  475. if ($result === false) return array();
  476. $array = array();
  477. while ($tmp=mysql_fetch_array($result,MYSQL_ASSOC)){
  478. $array[] = $tmp;
  479. }
  480. return $array;
  481. }
  482. /**
  483. * 显示建表语句
  484. *
  485. * @param string $table
  486. * @return string
  487. */
  488. public static function showCreateTable($table, $host = 'slave')
  489. {
  490. self::connect($host);
  491. $sql = 'SHOW CREATE TABLE `'.DBPRE.$table.'`';
  492. $result = self::query($sql,$host);
  493. if ($result === false) return '';
  494. $result = mysql_fetch_array($result,MYSQL_ASSOC);
  495. return $result['Create Table'];
  496. }
  497. /**
  498. * 显示表结构
  499. *
  500. * @param string $table
  501. * @return array
  502. */
  503. public static function showColumns($table, $host = 'slave')
  504. {
  505. self::connect($host);
  506. $sql = 'SHOW COLUMNS FROM `'.DBPRE.$table.'`';
  507. $result = self::query($sql,$host);
  508. if ($result === false) return array();
  509. $array = array();
  510. while ($tmp=mysql_fetch_array($result,MYSQL_ASSOC)){
  511. $array[$tmp['Field']] = array(
  512. 'name' => $tmp['Field'],
  513. 'type' => $tmp['Type'],
  514. 'null' => $tmp['Null'],
  515. 'default' => $tmp['Default'],
  516. 'primary' => (strtolower($tmp['Key']) == 'pri'),
  517. 'autoinc' => (strtolower($tmp['Extra']) == 'auto_increment'),
  518. );
  519. }
  520. return $array;
  521. }
  522. /**
  523. * 取得服务器信息
  524. *
  525. * @return string
  526. */
  527. public static function getServerInfo($host = 'slave'){
  528. self::connect($host);
  529. $result = mysql_get_server_info(self::$link[$host]);
  530. return $result;
  531. }
  532. /**
  533. * 格式化字段
  534. *
  535. * @param string $key 字段名
  536. * @return string
  537. */
  538. public static function parseKey(&$key){
  539. $key = trim($key);
  540. if(!preg_match('/[,\'\"\*\(\)`.\s]/',$key)) {
  541. $key = '`'.$key.'`';
  542. }
  543. return $key;
  544. }
  545. /**
  546. * 格式化值
  547. *
  548. * @param mixed $value
  549. * @return mixed
  550. */
  551. public static function parseValue($value){
  552. $value = addslashes(stripslashes($value));//重新加斜线,防止从数据库直接读取出错
  553. return "'".$value."'";
  554. }
  555. public static function beginTransaction($host = 'master'){
  556. self::connect($host);
  557. if (self::$iftransacte){
  558. mysql_query('START TRANSACTION',self::$link[$host]);
  559. self::$iftransacte = false;
  560. }
  561. }
  562. public static function commit($host = 'master'){
  563. if (!self::$iftransacte){
  564. $result = mysql_query('COMMIT',self::$link[$host]);
  565. self::$iftransacte = true;
  566. if (!$result) throw_exception("Db Error: ".mysql_error(self::$link[$host]));
  567. }
  568. }
  569. public static function rollback($host = 'master'){
  570. if (!self::$iftransacte){
  571. $result = mysql_query('ROLLBACK',self::$link[$host]);
  572. self::$iftransacte = true;
  573. if (!$result) throw_exception("Db Error: ".mysql_error(self::$link[$host]));
  574. }
  575. }
  576. public static function affected_rows($host = 'master') {
  577. self::connect($host);
  578. return mysql_affected_rows($host);
  579. }
  580. }