mysqli.php 22 KB

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