mysql.php 16 KB

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