mysql.php 17 KB

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