db.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. <?php
  2. /**
  3. * PDO类的封装,使用更方便,方法名称同微擎,不过需要类调用,在微擎内提取出来的
  4. $db = new Pdo('localhost','root','111','3306','tp','oauth_');
  5. var_dump($db->get('users'));
  6. $db->debug();//显示调试语句
  7. * date 2018.5.21
  8. * author yoby
  9. */
  10. class Db{
  11. protected $host;
  12. protected $username;
  13. protected $password;
  14. protected $post;
  15. protected $database;
  16. protected $tablepre;
  17. protected $db;
  18. protected $errors=array();
  19. public function __construct($host='localhost',$username='',$password='',$post='3306',$database='',$tablepre='ims_')
  20. {
  21. $this->host = $host;
  22. $this->username = $username;
  23. $this->password = $password;
  24. $this->post = $post;
  25. $this->database = $database;
  26. $this->tablepre=$tablepre;
  27. $this->db = new PDO("mysql:dbname={$database};host={$host};port={$post};charset=utf8", $username, $password);
  28. $sql = "SET NAMES 'utf8';";
  29. $this->db->exec($sql);
  30. $this->db->exec("SET sql_mode='';");
  31. }
  32. /**
  33. * 返回带前缀表名
  34. * @param $table 表名
  35. * @return string
  36. */
  37. public function tablename($table){
  38. return $this->tablepre .$table;
  39. }
  40. /**
  41. * 支持写操作的更新删除,不能查询
  42. * @param $sql
  43. * @param array $params
  44. * @return bool|int
  45. */
  46. public function query($sql, $params = array()) {
  47. $sqlsafe = SqlPaser::checkquery($sql);
  48. if (empty($params)) {
  49. $result = $this->db->exec($sql);
  50. $this->logging($sql, array(), $this->db->errorInfo());
  51. return $result;
  52. }
  53. $statement = $this->prepare($sql);
  54. $result = $statement->execute($params);
  55. $this->logging($sql, $params, $statement->errorInfo());
  56. if (!$result) {
  57. return false;
  58. } else {
  59. return $statement->rowCount();
  60. }
  61. }
  62. /**
  63. * 查询一条数据
  64. * @param $sql
  65. * @param array $params
  66. * @return bool|mixed
  67. */
  68. public function fetch($sql, $params = array()) {
  69. $statement = $this->prepare($sql);
  70. $result = $statement->execute($params);
  71. $this->logging($sql, $params, $statement->errorInfo());
  72. if (!$result) {
  73. return false;
  74. } else {
  75. $data = $statement->fetch(PDO::FETCH_ASSOC);
  76. return $data;
  77. }
  78. }
  79. /**
  80. * 查询多条数据
  81. * @param $sql
  82. * @param array $params
  83. * @param string $keyfield
  84. * @return array|bool
  85. */
  86. public function fetchall($sql, $params = array(), $keyfield = '') {
  87. $statement = $this->prepare($sql);
  88. $result = $statement->execute($params);
  89. $this->logging($sql, $params, $statement->errorInfo());
  90. if (!$result) {
  91. return false;
  92. } else {
  93. if (empty($keyfield)) {
  94. $result = $statement->fetchAll(pdo::FETCH_ASSOC);
  95. } else {
  96. $temp = $statement->fetchAll(pdo::FETCH_ASSOC);
  97. $result = array();
  98. if (!empty($temp)) {
  99. foreach ($temp as $key => &$row) {
  100. if (isset($row[$keyfield])) {
  101. $result[$row[$keyfield]] = $row;
  102. } else {
  103. $result[] = $row;
  104. }
  105. }
  106. }
  107. }
  108. return $result;
  109. }
  110. }
  111. /*
  112. * 返回数据第一条第N列
  113. */
  114. public function fetchcolumn($sql, $params = array(), $column = 0) {
  115. $statement = $this->prepare($sql);
  116. $result = $statement->execute($params);
  117. $this->logging($sql, $params, $statement->errorInfo());
  118. if (!$result) {
  119. return false;
  120. } else {
  121. $data = $statement->fetchColumn($column);
  122. return $data;
  123. }
  124. }
  125. /**
  126. * 查询一条记录,比fetch简单
  127. * @param $tablename表名不带前缀
  128. * @param array $params 查询数组
  129. * @param array $fields 要返回字段数组
  130. * @param array $orderby 排序字段数组
  131. * @return bool|mixed
  132. */
  133. public function get($tablename, $params = array(), $fields = array(), $orderby = array()) {
  134. $select = SqlPaser::parseSelect($fields);
  135. $condition = SqlPaser::parseParameter($params, 'AND');
  136. $orderbysql = SqlPaser::parseOrderby($orderby);
  137. $sql = "{$select} FROM " . $this->tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : '') . " $orderbysql LIMIT 1";
  138. return $this->fetch($sql, $condition['params']);
  139. }
  140. /**
  141. * 查询多条数据
  142. * @param $tablename 不含前缀表明
  143. * @param array $params 查询条件
  144. * @param array $fields
  145. * @param string $keyfield
  146. * @param array $orderby 排序
  147. * @param array $limit 限制条数
  148. * @return array|bool
  149. */
  150. public function getall($tablename, $params = array(), $fields = array(), $keyfield = '', $orderby = array(), $limit = array()) {
  151. $select = SqlPaser::parseSelect($fields);
  152. $condition = SqlPaser::parseParameter($params, 'AND');
  153. $limitsql = SqlPaser::parseLimit($limit);
  154. $orderbysql = SqlPaser::parseOrderby($orderby);
  155. $sql = "{$select} FROM " .$this->tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : '') . $orderbysql . $limitsql;
  156. return $this->fetchall($sql, $condition['params'], $keyfield);
  157. }
  158. /**
  159. * 查询区间记录
  160. * @param $tablename 表名不含前缀
  161. * @param array $params 查询条件数组
  162. * @param array $limit 区间条数
  163. * @param null $total
  164. * @param array $fields
  165. * @param string $keyfield
  166. * @param array $orderby
  167. * @return array|bool
  168. */
  169. public function getslice($tablename, $params = array(), $limit = array(), &$total = null, $fields = array(), $keyfield = '', $orderby = array()) {
  170. $select = SqlPaser::parseSelect($fields);
  171. $condition = SqlPaser::parseParameter($params, 'AND');
  172. $limitsql = SqlPaser::parseLimit($limit);
  173. if (!empty($orderby)) {
  174. if (is_array($orderby)) {
  175. $orderbysql = implode(',', $orderby);
  176. } else {
  177. $orderbysql = $orderby;
  178. }
  179. }
  180. $sql = "{$select} FROM " . $this->tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : '') . (!empty($orderbysql) ? " ORDER BY $orderbysql " : '') . $limitsql;
  181. $total = pdo_fetchcolumn("SELECT COUNT(*) FROM " . tablename($tablename) . (!empty($condition['fields']) ? " WHERE {$condition['fields']}" : ''), $condition['params']);
  182. return $this->fetchall($sql, $condition['params'], $keyfield);
  183. }
  184. /**
  185. * 返回单字段值
  186. * @param $tablename
  187. * @param array $params
  188. * @param string $field
  189. * @return bool|mixed
  190. */
  191. public function getcolumn($tablename, $params = array(), $field = '') {
  192. $result = $this->get($tablename, $params, $field);
  193. if (!empty($result)) {
  194. if (SqlPaser::strexists($field, '(')) {
  195. return array_shift($result);
  196. } else {
  197. return $result[$field];
  198. }
  199. } else {
  200. return false;
  201. }
  202. }
  203. /**
  204. * 更新操作
  205. * @param $table
  206. * @param array $data要更新数据
  207. * @param array $params 条件
  208. * @param string $glue
  209. * @return bool|int
  210. */
  211. public function update($table, $data = array(), $params = array(), $glue = 'AND') {
  212. $fields = SqlPaser::parseParameter($data, ',');
  213. $condition = SqlPaser::parseParameter($params, $glue);
  214. $params = array_merge($fields['params'], $condition['params']);
  215. $sql = "UPDATE " . $this->tablename($table) . " SET {$fields['fields']}";
  216. $sql .= $condition['fields'] ? ' WHERE '.$condition['fields'] : '';
  217. return $this->query($sql, $params);
  218. }
  219. /**
  220. * 插入数据
  221. * @param $table
  222. * @param array $data
  223. * @param bool $replace
  224. * @return bool|int
  225. */
  226. public function insert($table, $data = array(), $replace = FALSE) {
  227. $cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';
  228. $condition = SqlPaser::parseParameter($data, ',');
  229. return $this->query("$cmd " . $this->tablename($table) . " SET {$condition['fields']}", $condition['params']);
  230. }
  231. /*
  232. * 插入数据id
  233. */
  234. public function insertid() {
  235. return $this->db->lastInsertId();
  236. }
  237. /**
  238. * 删除
  239. * @param $table
  240. * @param array $params
  241. * @param string $glue
  242. * @return bool|int
  243. */
  244. public function delete($table, $params = array(), $glue = 'AND') {
  245. $condition = SqlPaser::parseParameter($params, $glue);
  246. $sql = "DELETE FROM " . $this->tablename($table);
  247. $sql .= $condition['fields'] ? ' WHERE '.$condition['fields'] : '';
  248. return $this->query($sql, $condition['params']);
  249. }
  250. /**
  251. * 检测表是否为空
  252. * @param $tablename
  253. * @param array $params
  254. * @return bool
  255. */
  256. public function exists($tablename, $params = array()) {
  257. $row = $this->get($tablename, $params);
  258. if (empty($row) || !is_array($row) || count($row) == 0) {
  259. return false;
  260. } else {
  261. return true;
  262. }
  263. }
  264. /**
  265. * 查询表中数据条数
  266. * @param $tablename
  267. * @param array $params
  268. * @param int $cachetime
  269. * @return int
  270. */
  271. public function count($tablename, $params = array(), $cachetime = 30) {
  272. $total = $this->getcolumn($tablename, $params, 'count(*)');
  273. return intval($total);
  274. }
  275. public function begin() {
  276. $this->db->beginTransaction();
  277. }
  278. public function commit() {
  279. $this->db->commit();
  280. }
  281. public function rollback() {
  282. $this->db->rollBack();
  283. }
  284. /*
  285. * 执行多条sql语句,建表常用
  286. * $sql sql语句
  287. * $stuff 数据表的前缀
  288. * */
  289. public function run($sql, $stuff = 'ims_') {
  290. if(!isset($sql) || empty($sql)) return;
  291. $sql = str_replace("\r", "\n", str_replace(' ' . $stuff, ' ' . $this->tablepre, $sql));
  292. $sql = str_replace("\r", "\n", str_replace(' `' . $stuff, ' `' . $this->tablepre, $sql));
  293. $ret = array();
  294. $num = 0;
  295. $sql = preg_replace("/\;[ \f\t\v]+/", ';', $sql);
  296. foreach(explode(";\n", trim($sql)) as $query) {
  297. $ret[$num] = '';
  298. $queries = explode("\n", trim($query));
  299. foreach($queries as $query) {
  300. $ret[$num] .= (isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0].$query[1] == '--') ? '' : $query;
  301. }
  302. $num++;
  303. }
  304. unset($sql);
  305. foreach($ret as $query) {
  306. $query = trim($query);
  307. if($query) {
  308. $this->query($query, array());
  309. }
  310. }
  311. }
  312. /**
  313. * 检测表中是否存在某个字段
  314. * @param $tablename
  315. * @param $fieldname
  316. * @return bool
  317. */
  318. public function fieldexists($tablename, $fieldname) {
  319. $isexists = $this->fetch("DESCRIBE " . $this->tablename($tablename) . " `{$fieldname}`", array());
  320. return !empty($isexists) ? true : false;
  321. }
  322. /**
  323. * 检测表是否存在
  324. * @param $table
  325. * @return bool
  326. */
  327. public function tableexists($table) {
  328. if(!empty($table)) {
  329. $data = $this->fetch("SHOW TABLES LIKE '{$this->tablepre}{$table}'", array());
  330. if(!empty($data)) {
  331. $data = array_values($data);
  332. $tablename = $this->tablepre . $table;
  333. if(in_array($tablename, $data)) {
  334. return true;
  335. } else {
  336. return false;
  337. }
  338. } else {
  339. return false;
  340. }
  341. } else {
  342. return false;
  343. }
  344. }
  345. /**
  346. * 检测表中是否存在某个索引
  347. * @param $tablename
  348. * @param $indexname
  349. * @return bool
  350. */
  351. public function indexexists($tablename, $indexname) {
  352. if (!empty($indexname)) {
  353. $indexs = $this->fetchall("SHOW INDEX FROM " . $this->tablename($tablename), array(), '');
  354. if (!empty($indexs) && is_array($indexs)) {
  355. foreach ($indexs as $row) {
  356. if ($row['Key_name'] == $indexname) {
  357. return true;
  358. }
  359. }
  360. }
  361. }
  362. return false;
  363. }
  364. public function prepare($sql) {
  365. $sqlsafe = SqlPaser::checkquery($sql);
  366. $statement = $this->db->prepare($sql);
  367. return $statement;
  368. }
  369. private function logging($sql, $params = array(), $message = '') {
  370. if(TRUE) {
  371. $info = array();
  372. $info['sql'] = $sql;
  373. $info['params'] = $params;
  374. $info['error'] = empty($message) ? $this->pdo->errorInfo() : $message;
  375. $this->debug(false, $info);
  376. }
  377. return true;
  378. }
  379. /**
  380. * 显示debug
  381. * @param bool $output
  382. * @param array $append
  383. * @return array
  384. */
  385. public function debug($output = true, $append = array()) {
  386. if(!empty($append)) {
  387. $output = false;
  388. array_push($this->errors, $append);
  389. }
  390. if($output) {
  391. echo '<pre>'.print_r($this->errors,TRUE).'</pre>';
  392. } else {
  393. if (!empty($append['error'][1])) {
  394. $traces = debug_backtrace();
  395. $ts = '';
  396. foreach($traces as $trace) {
  397. $trace['file'] = str_replace('\\', '/', $trace['file']);
  398. $ts .= "file: {$trace['file']}; line: {$trace['line']}; <br />";
  399. }
  400. $params = var_export($append['params'], true);
  401. trigger_error("SQL: <br/>{$append['sql']}<hr/>Params: <br/>{$params}<hr/>SQL Error: <br/>{$append['error'][2]}<hr/>Traces: <br/>{$ts}", E_USER_NOTICE);
  402. }
  403. }
  404. return $this->errors;
  405. }
  406. }
  407. class SqlPaser {
  408. private static $checkcmd = array('SELECT', 'UPDATE', 'INSERT', 'REPLAC', 'DELETE');
  409. private static $disable = array(
  410. 'function' => array('load_file', 'floor', 'hex', 'substring', 'if', 'ord', 'char', 'benchmark', 'reverse', 'strcmp', 'datadir', 'updatexml', 'extractvalue', 'name_const', 'multipoint', 'database', 'user'),
  411. 'action' => array('@', 'intooutfile', 'intodumpfile', 'unionselect', 'uniondistinct', 'information_schema', 'current_user', 'current_date'),
  412. 'note' => array('/*','*/','#','--'),
  413. );
  414. public static function strexists($string, $find) {
  415. return !(strpos($string, $find) === FALSE);
  416. }
  417. public static function checkquery($sql) {
  418. $cmd = strtoupper(substr(trim($sql), 0, 6));
  419. if (in_array($cmd, self::$checkcmd)) {
  420. $mark = $clean = '';
  421. $sql = str_replace(array('\\\\', '\\\'', '\\"', '\'\''), '', $sql);
  422. if (strpos($sql, '/') === false && strpos($sql, '#') === false && strpos($sql, '-- ') === false && strpos($sql, '@') === false && strpos($sql, '`') === false) {
  423. $cleansql = preg_replace("/'(.+?)'/s", '', $sql);
  424. } else {
  425. $cleansql = self::stripSafeChar($sql);
  426. }
  427. $cleansql = preg_replace("/[^a-z0-9_\-\(\)#\*\/\"]+/is", "", strtolower($cleansql));
  428. if (is_array(self::$disable['function'])) {
  429. foreach (self::$disable['function'] as $fun) {
  430. if (strpos($cleansql, $fun . '(') !== false) {
  431. return error(1, 'SQL中包含禁用函数 - ' . $fun);
  432. }
  433. }
  434. }
  435. if (is_array(self::$disable['action'])) {
  436. foreach (self::$disable['action'] as $action) {
  437. if (strpos($cleansql, $action) !== false) {
  438. return error(2, 'SQL中包含禁用操作符 - ' . $action);
  439. }
  440. }
  441. }
  442. if (is_array(self::$disable['note'])) {
  443. foreach (self::$disable['note'] as $note) {
  444. if (strpos($cleansql, $note) !== false) {
  445. return error(3, 'SQL中包含注释信息');
  446. }
  447. }
  448. }
  449. } elseif (substr($cmd, 0, 2) === '/*') {
  450. return error(3, 'SQL中包含注释信息');
  451. }
  452. }
  453. private static function stripSafeChar($sql) {
  454. $len = strlen($sql);
  455. $mark = $clean = '';
  456. for ($i = 0; $i < $len; $i++) {
  457. $str = $sql[$i];
  458. switch ($str) {
  459. case '\'':
  460. if (!$mark) {
  461. $mark = '\'';
  462. $clean .= $str;
  463. } elseif ($mark == '\'') {
  464. $mark = '';
  465. }
  466. break;
  467. case '/':
  468. if (empty($mark) && $sql[$i + 1] == '*') {
  469. $mark = '/*';
  470. $clean .= $mark;
  471. $i++;
  472. } elseif ($mark == '/*' && $sql[$i - 1] == '*') {
  473. $mark = '';
  474. $clean .= '*';
  475. }
  476. break;
  477. case '#':
  478. if (empty($mark)) {
  479. $mark = $str;
  480. $clean .= $str;
  481. }
  482. break;
  483. case "\n":
  484. if ($mark == '#' || $mark == '--') {
  485. $mark = '';
  486. }
  487. break;
  488. case '-':
  489. if (empty($mark) && substr($sql, $i, 3) == '-- ') {
  490. $mark = '-- ';
  491. $clean .= $mark;
  492. }
  493. break;
  494. default:
  495. break;
  496. }
  497. $clean .= $mark ? '' : $str;
  498. }
  499. return $clean;
  500. }
  501. public static function parseParameter($params, $glue = ',', $alias = '') {
  502. $result = array('fields' => ' 1 ', 'params' => array());
  503. $split = '';
  504. $suffix = '';
  505. $allow_operator = array('>', '<', '<>', '!=', '>=', '<=', '+=', '-=', 'LIKE', 'like');
  506. if (in_array(strtolower($glue), array('and', 'or'))) {
  507. $suffix = '__';
  508. }
  509. if (!is_array($params)) {
  510. $result['fields'] = $params;
  511. return $result;
  512. }
  513. if (is_array($params)) {
  514. $result['fields'] = '';
  515. foreach ($params as $fields => $value) {
  516. if ($glue == ',') {
  517. $value = $value === null ? '' : $value;
  518. }
  519. $operator = '';
  520. if (strpos($fields, ' ') !== FALSE) {
  521. list($fields, $operator) = explode(' ', $fields, 2);
  522. if (!in_array($operator, $allow_operator)) {
  523. $operator = '';
  524. }
  525. }
  526. if (empty($operator)) {
  527. $fields = trim($fields);
  528. if (is_array($value) && !empty($value)) {
  529. $operator = 'IN';
  530. } elseif ($value === null) {
  531. $operator = 'IS';
  532. } else {
  533. $operator = '=';
  534. }
  535. } elseif ($operator == '+=') {
  536. $operator = " = `$fields` + ";
  537. } elseif ($operator == '-=') {
  538. $operator = " = `$fields` - ";
  539. } elseif ($operator == '!=' || $operator == '<>') {
  540. if (is_array($value) && !empty($value)) {
  541. $operator = 'NOT IN';
  542. } elseif ($value === null) {
  543. $operator = 'IS NOT';
  544. }
  545. }
  546. $select_fields = self::parseFieldAlias($fields, $alias);
  547. if (is_array($value) && !empty($value)) {
  548. $insql = array();
  549. $value = array_values($value);
  550. foreach ($value as $v) {
  551. $placeholder = self::parsePlaceholder($fields, $suffix);
  552. $insql[] = $placeholder;
  553. $result['params'][$placeholder] = is_null($v) ? '' : $v;
  554. }
  555. $result['fields'] .= $split . "$select_fields {$operator} (".implode(",", $insql).")";
  556. $split = ' ' . $glue . ' ';
  557. } else {
  558. $placeholder = self::parsePlaceholder($fields, $suffix);
  559. $result['fields'] .= $split . "$select_fields {$operator} " . (is_null($value) ? 'NULL' : $placeholder);
  560. $split = ' ' . $glue . ' ';
  561. if (!is_null($value)) {
  562. $result['params'][$placeholder] = is_array($value) ? '' : $value;
  563. }
  564. }
  565. }
  566. }
  567. return $result;
  568. }
  569. private static function parsePlaceholder($field, $suffix = '') {
  570. static $params_index = 0;
  571. $params_index++;
  572. $illegal_str = array('(', ')', '.', '*');
  573. $placeholder = ":{$suffix}" . str_replace($illegal_str, '_', $field) . "_{$params_index}";
  574. return $placeholder;
  575. }
  576. private static function parseFieldAlias($field, $alias = '') {
  577. if (self::strexists($field, '.') || self::strexists($field, '*')) {
  578. return $field;
  579. }
  580. if (self::strexists($field, '(')) {
  581. $select_fields = str_replace(array('(', ')'), array('(' . (!empty($alias) ? "`{$alias}`." : '') .'`', '`)'), $field);
  582. } else {
  583. $select_fields = (!empty($alias) ? "`{$alias}`." : '') . "`$field`";
  584. }
  585. return $select_fields;
  586. }
  587. public static function parseSelect($field = array(), $alias = '') {
  588. if (empty($field) || $field == '*') {
  589. return ' SELECT *';
  590. }
  591. if (!is_array($field)) {
  592. $field = array($field);
  593. }
  594. $select = array();
  595. $index = 0;
  596. foreach ($field as $field_row) {
  597. if (self::strexists($field_row, '*')) {
  598. if (!self::strexists(strtolower($field_row), 'as')) {
  599. }
  600. } elseif (self::strexists(strtolower($field_row), 'select')) {
  601. if ($field_row[0] != '(') {
  602. $field_row = "($field_row) AS '{$index}'";
  603. }
  604. } elseif (self::strexists($field_row, '(')) {
  605. $field_row = str_replace(array('(', ')'), array('(' . (!empty($alias) ? "`{$alias}`." : '') . '`', '`)'), $field_row);
  606. if (!self::strexists(strtolower($field_row), 'as')) {
  607. $field_row .= " AS '{$index}'";
  608. }
  609. } else {
  610. $field_row = self::parseFieldAlias($field_row, $alias);
  611. }
  612. $select[] = $field_row;
  613. $index++;
  614. }
  615. return " SELECT " . implode(',', $select);
  616. }
  617. public static function parseLimit($limit, $inpage = true) {
  618. $limitsql = '';
  619. if (empty($limit)) {
  620. return $limitsql;
  621. }
  622. if (is_array($limit)) {
  623. if (empty($limit[0]) && !empty($limit[1])) {
  624. $limitsql = " LIMIT " . $limit[1];
  625. } else {
  626. $limit[0] = max(intval($limit[0]), 1);
  627. !empty($limit[1]) && $limit[1] = max(intval($limit[1]), 1);
  628. if (empty($limit[0]) && empty($limit[1])) {
  629. $limitsql = '';
  630. } elseif (!empty($limit[0]) && empty($limit[1])) {
  631. $limitsql = " LIMIT " . $limit[0];
  632. } else {
  633. $limitsql = " LIMIT " . ($inpage ? ($limit[0] - 1) * $limit[1] : $limit[0]) . ', ' . $limit[1];
  634. }
  635. }
  636. } else {
  637. $limit = trim($limit);
  638. if (preg_match('/^(?:limit)?[\s,0-9]+$/i', $limit)) {
  639. $limitsql = self::strexists(strtoupper($limit), 'LIMIT') ? " $limit " : " LIMIT $limit";
  640. }
  641. }
  642. return $limitsql;
  643. }
  644. public static function parseOrderby($orderby, $alias = '') {
  645. $orderbysql = '';
  646. if (empty($orderby)) {
  647. return $orderbysql;
  648. }
  649. if (!is_array($orderby)) {
  650. $orderby = explode(',', $orderby);
  651. }
  652. foreach ($orderby as $i => &$row) {
  653. $row = strtolower($row);
  654. list($field, $orderbyrule) = explode(' ', $row);
  655. if ($orderbyrule != 'asc' && $orderbyrule != 'desc') {
  656. unset($orderby[$i]);
  657. }
  658. $field = self::parseFieldAlias($field, $alias);
  659. $row = "{$field} {$orderbyrule}";
  660. }
  661. $orderbysql = implode(',', $orderby);
  662. return !empty($orderbysql) ? " ORDER BY $orderbysql " : '';
  663. }
  664. public static function parseGroupby($statement, $alias = '') {
  665. if (empty($statement)) {
  666. return $statement;
  667. }
  668. if (!is_array($statement)) {
  669. $statement = explode(',', $statement);
  670. }
  671. foreach ($statement as $i => &$row) {
  672. $row = self::parseFieldAlias($row, $alias);
  673. if (self::strexists($row, ' ')) {
  674. unset($statement[$i]);
  675. }
  676. }
  677. $statementsql = implode(', ', $statement);
  678. return !empty($statementsql) ? " GROUP BY $statementsql " : '';
  679. }
  680. }
  681. $db = new Db('121.42.172.1','root','mysqlmysql','3306','weui','ims_');