mysqli.php 22 KB

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