mysqli.php 22 KB

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