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