mysql.php 17 KB

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