mysqli.php 21 KB

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