db_mysqli.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php
  2. /**
  3. * db_mysqli.class.php MYSQLI数据库实现类
  4. *
  5. * @copyright (C) 2005-2015 PHPCMS
  6. * @license http://www.phpcms.cn/license/
  7. * @lastmodify 2016-02-01
  8. */
  9. final class db_mysqli {
  10. /**
  11. * 数据库配置信息
  12. */
  13. private $config = null;
  14. /**
  15. * 数据库连接资源句柄
  16. */
  17. public $link = null;
  18. /**
  19. * 最近一次查询资源句柄
  20. */
  21. public $lastqueryid = null;
  22. /**
  23. * 统计数据库查询次数
  24. */
  25. public $querycount = 0;
  26. public function __construct() {
  27. }
  28. /**
  29. * 打开数据库连接,有可能不真实连接数据库
  30. * @param $config 数据库连接参数
  31. *
  32. * @return void
  33. */
  34. public function open($config) {
  35. $this->config = $config;
  36. if($config['autoconnect'] == 1) {
  37. $this->connect();
  38. }
  39. }
  40. /**
  41. * 真正开启数据库连接
  42. *
  43. * @return void
  44. */
  45. public function connect() {
  46. $this->link = new mysqli($this->config['hostname'], $this->config['username'], $this->config['password'], $this->config['database'], $this->config['port']?intval($this->config['port']):3306);
  47. if(mysqli_connect_error()){
  48. $this->halt('Can not connect to MySQL server');
  49. return false;
  50. }
  51. if($this->version() > '4.1') {
  52. $charset = isset($this->config['charset']) ? $this->config['charset'] : '';
  53. $serverset = $charset ? "character_set_connection='$charset',character_set_results='$charset',character_set_client=binary" : '';
  54. $serverset .= $this->version() > '5.0.1' ? ((empty($serverset) ? '' : ',')." sql_mode='' ") : '';
  55. $serverset && $this->link->query("SET $serverset");
  56. }
  57. return $this->link;
  58. }
  59. /**
  60. * 数据库查询执行方法
  61. * @param $sql 要执行的sql语句
  62. * @return 查询资源句柄
  63. */
  64. private function execute($sql) {
  65. if(!is_object($this->link)) {
  66. $this->connect();
  67. }
  68. $this->lastqueryid = $this->link->query($sql) or $this->halt($this->link->error, $sql);
  69. $this->querycount++;
  70. return $this->lastqueryid;
  71. }
  72. /**
  73. * 执行sql查询
  74. * @param $data 需要查询的字段值[例`name`,`gender`,`birthday`]
  75. * @param $table 数据表
  76. * @param $where 查询条件[例`name`='$name']
  77. * @param $limit 返回结果范围[例:10或10,10 默认为空]
  78. * @param $order 排序方式 [默认按数据库默认方式排序]
  79. * @param $group 分组方式 [默认为空]
  80. * @param $key 返回数组按键名排序
  81. * @return array 查询结果集数组
  82. */
  83. public function select($data, $table, $where = '', $limit = '', $order = '', $group = '', $key = '') {
  84. $where = $where == '' ? '' : ' WHERE '.$where;
  85. $order = $order == '' ? '' : ' ORDER BY '.$order;
  86. $group = $group == '' ? '' : ' GROUP BY '.$group;
  87. $limit = $limit == '' ? '' : ' LIMIT '.$limit;
  88. $field = explode(',', $data);
  89. array_walk($field, array($this, 'add_special_char'));
  90. $data = implode(',', $field);
  91. $sql = 'SELECT '.$data.' FROM `'.$this->config['database'].'`.`'.$table.'`'.$where.$group.$order.$limit;
  92. $this->execute($sql);
  93. if(!is_object($this->lastqueryid)) {
  94. return $this->lastqueryid;
  95. }
  96. $datalist = array();
  97. while(($rs = $this->fetch_next()) != false) {
  98. if($key) {
  99. $datalist[$rs[$key]] = $rs;
  100. } else {
  101. $datalist[] = $rs;
  102. }
  103. }
  104. $this->free_result();
  105. return $datalist;
  106. }
  107. /**
  108. * 获取单条记录查询
  109. * @param $data 需要查询的字段值[例`name`,`gender`,`birthday`]
  110. * @param $table 数据表
  111. * @param $where 查询条件
  112. * @param $order 排序方式 [默认按数据库默认方式排序]
  113. * @param $group 分组方式 [默认为空]
  114. * @return array/null 数据查询结果集,如果不存在,则返回空
  115. */
  116. public function get_one($data, $table, $where = '', $order = '', $group = '') {
  117. $where = $where == '' ? '' : ' WHERE '.$where;
  118. $order = $order == '' ? '' : ' ORDER BY '.$order;
  119. $group = $group == '' ? '' : ' GROUP BY '.$group;
  120. $limit = ' LIMIT 1';
  121. $field = explode( ',', $data);
  122. array_walk($field, array($this, 'add_special_char'));
  123. $data = implode(',', $field);
  124. $sql = 'SELECT '.$data.' FROM `'.$this->config['database'].'`.`'.$table.'`'.$where.$group.$order.$limit;
  125. $this->execute($sql);
  126. $res = $this->fetch_next();
  127. $this->free_result();
  128. return $res;
  129. }
  130. /**
  131. * 遍历查询结果集
  132. * @param $type 返回结果集类型
  133. * MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH
  134. * @return array
  135. */
  136. public function fetch_next($type=MYSQLI_ASSOC) {
  137. $res = $this->lastqueryid->fetch_array($type);
  138. if(!$res) {
  139. $this->free_result();
  140. }
  141. return $res;
  142. }
  143. /**
  144. * 释放查询资源
  145. * @return void
  146. */
  147. public function free_result() {
  148. if(is_resource($this->lastqueryid)) {
  149. $this->lastqueryid->free();
  150. $this->lastqueryid = null;
  151. }
  152. }
  153. /**
  154. * 直接执行sql查询
  155. * @param $sql 查询sql语句
  156. * @return boolean/query resource 如果为查询语句,返回资源句柄,否则返回true/false
  157. */
  158. public function query($sql) {
  159. return $this->execute($sql);
  160. }
  161. /**
  162. * 执行添加记录操作
  163. * @param $data 要增加的数据,参数为数组。数组key为字段值,数组值为数据取值
  164. * @param $table 数据表
  165. * @return boolean
  166. */
  167. public function insert($data, $table, $return_insert_id = false, $replace = false) {
  168. if(!is_array( $data ) || $table == '' || count($data) == 0) {
  169. return false;
  170. }
  171. $fielddata = array_keys($data);
  172. $valuedata = array_values($data);
  173. array_walk($fielddata, array($this, 'add_special_char'));
  174. array_walk($valuedata, array($this, 'escape_string'));
  175. $field = implode (',', $fielddata);
  176. $value = implode (',', $valuedata);
  177. $cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';
  178. $sql = $cmd.' `'.$this->config['database'].'`.`'.$table.'`('.$field.') VALUES ('.$value.')';
  179. $return = $this->execute($sql);
  180. return $return_insert_id ? $this->insert_id() : $return;
  181. }
  182. /**
  183. * 获取最后一次添加记录的主键号
  184. * @return int
  185. */
  186. public function insert_id() {
  187. if(!is_object($this->link)) {
  188. $this->connect();
  189. }
  190. return $this->link->insert_id;
  191. }
  192. /**
  193. * 执行更新记录操作
  194. * @param $data 要更新的数据内容,参数可以为数组也可以为字符串,建议数组。
  195. * 为数组时数组key为字段值,数组值为数据取值
  196. * 为字符串时[例:`name`='phpcms',`hits`=`hits`+1]。
  197. * 为数组时[例: array('name'=>'phpcms','password'=>'123456')]
  198. * 数组可使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1
  199. * @param $table 数据表
  200. * @param $where 更新数据时的条件
  201. * @return boolean
  202. */
  203. public function update($data, $table, $where = '') {
  204. if($table == '' or $where == '') {
  205. return false;
  206. }
  207. $where = ' WHERE '.$where;
  208. $field = '';
  209. if(is_string($data) && $data != '') {
  210. $field = $data;
  211. } elseif (is_array($data) && count($data) > 0) {
  212. $fields = array();
  213. foreach($data as $k=>$v) {
  214. switch (substr($v, 0, 2)) {
  215. case '+=':
  216. $v = substr($v,2);
  217. if (is_numeric($v)) {
  218. $fields[] = $this->add_special_char($k).'='.$this->add_special_char($k).'+'.$this->escape_string($v, '', false);
  219. } else {
  220. continue;
  221. }
  222. break;
  223. case '-=':
  224. $v = substr($v,2);
  225. if (is_numeric($v)) {
  226. $fields[] = $this->add_special_char($k).'='.$this->add_special_char($k).'-'.$this->escape_string($v, '', false);
  227. } else {
  228. continue;
  229. }
  230. break;
  231. default:
  232. $fields[] = $this->add_special_char($k).'='.$this->escape_string($v);
  233. }
  234. }
  235. $field = implode(',', $fields);
  236. } else {
  237. return false;
  238. }
  239. $sql = 'UPDATE `'.$this->config['database'].'`.`'.$table.'` SET '.$field.$where;
  240. return $this->execute($sql);
  241. }
  242. /**
  243. * 执行删除记录操作
  244. * @param $table 数据表
  245. * @param $where 删除数据条件,不充许为空。
  246. * 如果要清空表,使用empty方法
  247. * @return boolean
  248. */
  249. public function delete($table, $where) {
  250. if ($table == '' || $where == '') {
  251. return false;
  252. }
  253. $where = ' WHERE '.$where;
  254. $sql = 'DELETE FROM `'.$this->config['database'].'`.`'.$table.'`'.$where;
  255. return $this->execute($sql);
  256. }
  257. /**
  258. * 获取最后数据库操作影响到的条数
  259. * @return int
  260. */
  261. public function affected_rows() {
  262. if(!is_object($this->link)) {
  263. $this->connect();
  264. }
  265. return $this->link->affected_rows;
  266. }
  267. /**
  268. * 获取数据表主键
  269. * @param $table 数据表
  270. * @return array
  271. */
  272. public function get_primary($table) {
  273. $this->execute("SHOW COLUMNS FROM $table");
  274. while($r = $this->fetch_next()) {
  275. if($r['Key'] == 'PRI') break;
  276. }
  277. return $r['Field'];
  278. }
  279. /**
  280. * 获取表字段
  281. * @param $table 数据表
  282. * @return array
  283. */
  284. public function get_fields($table) {
  285. $fields = array();
  286. $this->execute("SHOW COLUMNS FROM $table");
  287. while($r = $this->fetch_next()) {
  288. $fields[$r['Field']] = $r['Type'];
  289. }
  290. return $fields;
  291. }
  292. /**
  293. * 检查不存在的字段
  294. * @param $table 表名
  295. * @return array
  296. */
  297. public function check_fields($table, $array) {
  298. $fields = $this->get_fields($table);
  299. $nofields = array();
  300. foreach($array as $v) {
  301. if(!array_key_exists($v, $fields)) {
  302. $nofields[] = $v;
  303. }
  304. }
  305. return $nofields;
  306. }
  307. /**
  308. * 检查表是否存在
  309. * @param $table 表名
  310. * @return boolean
  311. */
  312. public function table_exists($table) {
  313. $tables = $this->list_tables();
  314. return in_array($table, $tables) ? 1 : 0;
  315. }
  316. public function list_tables() {
  317. $tables = array();
  318. $this->execute("SHOW TABLES");
  319. while($r = $this->fetch_next()) {
  320. $tables[] = $r['Tables_in_'.$this->config['database']];
  321. }
  322. return $tables;
  323. }
  324. /**
  325. * 检查字段是否存在
  326. * @param $table 表名
  327. * @return boolean
  328. */
  329. public function field_exists($table, $field) {
  330. $fields = $this->get_fields($table);
  331. return array_key_exists($field, $fields);
  332. }
  333. public function num_rows($sql) {
  334. $this->lastqueryid = $this->execute($sql);
  335. return $this->lastqueryid ? $this->lastqueryid->num_rows : 0;
  336. }
  337. public function num_fields($sql) {
  338. $this->lastqueryid = $this->execute($sql);
  339. return $this->lastqueryid ? $this->lastqueryid->field_count : null;
  340. }
  341. public function result($sql, $row) {
  342. $this->lastqueryid = $this->execute($sql);
  343. $this->lastqueryid->data_seek($row);
  344. $assocs = $this->lastqueryid->fetch_row();
  345. return $assocs[0];
  346. }
  347. public function error() {
  348. if(!is_object($this->link)) {
  349. $this->connect();
  350. }
  351. return $this->link->error;
  352. }
  353. public function errno() {
  354. if(!is_object($this->link)) {
  355. $this->connect();
  356. }
  357. return intval($this->link->errno);
  358. }
  359. public function version() {
  360. if(!is_object($this->link)) {
  361. $this->connect();
  362. }
  363. return $this->link->server_info;//server_version
  364. }
  365. public function close() {
  366. if ($this->link) {
  367. $this->link->close();
  368. }
  369. $this->link = null;
  370. }
  371. public function escape($str){
  372. if(!is_object($this->link)) {
  373. $this->connect();
  374. }
  375. return $this->link->real_escape_string($str);
  376. }
  377. public function halt($message = '', $sql = '') {
  378. if($this->config['debug']) {
  379. $this->errormsg = "<b>MySQL Query : </b> $sql <br /><b> MySQL Error : </b>".$this->error()." <br /> <b>MySQL Errno : </b>".$this->errno()." <br /><b> Message : </b> $message <br /><a href='http://faq.phpcms.cn/?errno=".$this->errno()."&msg=".urlencode($this->error())."' target='_blank' style='color:red'>Need Help?</a>";
  380. $msg = $this->errormsg;
  381. echo '<div style="font-size:12px;text-align:left; border:1px solid #9cc9e0; padding:1px 4px;color:#000000;font-family:Arial, Helvetica,sans-serif;"><span>'.$msg.'</span></div>';
  382. exit;
  383. } else {
  384. return false;
  385. }
  386. }
  387. /**
  388. * 对字段两边加反引号,以保证数据库安全
  389. * @param $value 数组值
  390. */
  391. public function add_special_char(&$value) {
  392. if('*' == $value || false !== strpos($value, '(') || false !== strpos($value, '.') || false !== strpos ( $value, '`')) {
  393. //不处理包含* 或者 使用了sql方法。
  394. } else {
  395. $value = '`'.trim($value).'`';
  396. }
  397. if (preg_match("/\b(select|insert|update|delete)\b/i", $value)) {
  398. $value = preg_replace("/\b(select|insert|update|delete)\b/i", '', $value);
  399. }
  400. return $value;
  401. }
  402. /**
  403. * 对字段值两边加引号,以保证数据库安全
  404. * @param $value 数组值
  405. * @param $key 数组key
  406. * @param $quotation
  407. */
  408. public function escape_string(&$value, $key='', $quotation = 1) {
  409. if ($quotation) {
  410. $q = '\'';
  411. } else {
  412. $q = '';
  413. }
  414. $value = $q.$value.$q;
  415. return $value;
  416. }
  417. }
  418. ?>