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