mysqli.php 22 KB

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