php链式操作mysql数据库(封装类带使用示例)

后端开发   发布日期:2025年05月24日   浏览次数:165

本文代码将一些简单常用的SQL语句,拆分、封装成链式函数与终结函数,链式操作没有先后之分,实现傻瓜式mysql数据库操作。 同时学习下静态成员函数,实现链式操作的具体语法。

链式操作是利用运算符进行连续操作。它的特点是一条语句中出现两个或两个以上相同的操作符。链式操作,说白了其实就是链式的调用对象的方法。既然要实现字符串的链式操作,那么就要实现一个字符串类,然后对这个类的对象进行调用操作。时代在变迁,技术不断进度,代码既要好用,还得优雅。相比传统调用方法,采用链式操作后,一步到位。

封装类常用操作使用示例

  1. // 初始化db连接
  2. $db = new \Workerman\MySQL\Connection('host', 'port', 'user', 'password', 'db_name');
  3.  
  4. // 获取所有数据
  5. $db->select('ID,Sex')->from('Persons')->where('sex= :sex AND ID = :id')->bindValues(array('sex'=>'M', 'id' => 1))->query();
  6. //等价于
  7. $db->select('ID,Sex')->from('Persons')->where("sex= 'M' AND ID = 1")->query();
  8. //等价于
  9. $db->query("SELECT ID,Sex FROM `Persons` WHERE sex='M' AND ID = 1");
  10.  
  11. // 获取一行数据
  12. $db->select('ID,Sex')->from('Persons')->where('sex= :sex')->bindValues(array('sex'=>'M'))->row();
  13. //等价于
  14. $db->select('ID,Sex')->from('Persons')->where("sex= 'M' ")->row();
  15. //等价于
  16. $db->row("SELECT ID,Sex FROM `Persons` WHERE sex='M'");
  17.  
  18. // 获取一列数据
  19. $db->select('ID')->from('Persons')->where('sex= :sex')->bindValues(array('sex'=>'M'))->column();
  20. //等价于
  21. $db->select('ID')->from('Persons')->where("sex= 'F' ")->column();
  22. //等价于
  23. $db->column("SELECT `ID` FROM `Persons` WHERE sex='M'");
  24.  
  25. // 获取单个值
  26. $db->select('ID')->from('Persons')->where('sex= :sex')->bindValues(array('sex'=>'M'))->single();
  27. //等价于
  28. $db->select('ID')->from('Persons')->where("sex= 'F' ")->single();
  29. //等价于
  30. $db->single("SELECT ID FROM `Persons` WHERE sex='M'");
  31.  
  32. // 复杂查询
  33. $db->select('*')->from('table1')->innerJoin('table2','table1.uid = table2.uid')->where('age > :age')->groupBy(array('aid'))->having('foo="foo"')->orderByASC/*orderByDESC*/(array('did'))
  34. ->limit(10)->offset(20)->bindValues(array('age' => 13));
  35. // 等价于
  36. $db->query('SELECT * FROM `table1` INNER JOIN `table2` ON `table1`.`uid` = `table2`.`uid`
  37. WHERE age > 13 GROUP BY aid HAVING foo="foo" ORDER BY did LIMIT 10 OFFSET 20');
  38.  
  39. // 插入
  40. $insert_id = $db->insert('Persons')->cols(array(
  41. 'Firstname'=>'abc',
  42. 'Lastname'=>'efg',
  43. 'Sex'=>'M',
  44. 'Age'=>13))->query();
  45. 等价于
  46. $insert_id = $db->query("INSERT INTO `Persons` ( `Firstname`,`Lastname`,`Sex`,`Age`)
  47. VALUES ( 'abc', 'efg', 'M', 13)");
  48.  
  49. // 更新
  50. $row_count = $db->update('Persons')->cols(array('sex'))->where('ID=1')
  51. ->bindValue('sex', 'F')->query();
  52. // 等价于
  53. $row_count = $db->update('Persons')->cols(array('sex'=>'F'))->where('ID=1')->query();
  54. // 等价于
  55. $row_count = $db->query("UPDATE `Persons` SET `sex` = 'F' WHERE ID=1");
  56.  
  57. // 删除
  58. $row_count = $db->delete('Persons')->where('ID=9')->query();
  59. // 等价于
  60. $row_count = $db->query("DELETE FROM `Persons` WHERE ID=9");
  61.  
  62. // 事务
  63. $db->beginTrans();
  64. ....
  65. $db->commitTrans(); // or $db->rollBackTrans();

封装源码(保存文件引用)

  1. <?php
  2. /**
  3. * 数据库连接类,依赖 PDO_MYSQL 扩展
  4. * 在 https://github.com/auraphp/Aura.SqlQuery 的基础上修改而成
  5. */
  6. class Connection
  7. {
  8. /**
  9. * SELECT
  10. *
  11. * @var array
  12. */
  13. protected $union = array();
  14.  
  15. /**
  16. * 是否是更新
  17. *
  18. * @var bool
  19. */
  20. protected $for_update = false;
  21.  
  22. /**
  23. * 选择的列
  24. *
  25. * @var array
  26. */
  27. protected $cols = array();
  28.  
  29. /**
  30. * 从哪些表里面 SELECT
  31. *
  32. * @var array
  33. */
  34. protected $from = array();
  35.  
  36. /**
  37. * $from 当前的 key
  38. *
  39. * @var int
  40. */
  41. protected $from_key = -1;
  42.  
  43. /**
  44. * GROUP BY 的列
  45. *
  46. * @var array
  47. */
  48. protected $group_by = array();
  49.  
  50. /**
  51. * HAVING 条件数组.
  52. *
  53. * @var array
  54. */
  55. protected $having = array();
  56.  
  57. /**
  58. * HAVING 语句中绑定的值.
  59. *
  60. * @var array
  61. */
  62. protected $bind_having = array();
  63.  
  64. /**
  65. * 每页多少条记录
  66. *
  67. * @var int
  68. */
  69. protected $paging = 10;
  70.  
  71. /**
  72. * sql 中绑定的值
  73. *
  74. * @var array
  75. */
  76. protected $bind_values = array();
  77.  
  78. /**
  79. * WHERE 条件.
  80. *
  81. * @var array
  82. */
  83. protected $where = array();
  84.  
  85. /**
  86. * WHERE 语句绑定的值
  87. *
  88. * @var array
  89. */
  90. protected $bind_where = array();
  91.  
  92. /**
  93. * ORDER BY 的列
  94. *
  95. * @var array
  96. */
  97. protected $order_by = array();
  98.  
  99. /**
  100. * ORDER BY 的排序方式,默认为升序
  101. *
  102. * @var bool
  103. */
  104. protected $order_asc = true;
  105. /**
  106. * SELECT 多少记录
  107. *
  108. * @var int
  109. */
  110. protected $limit = 0;
  111.  
  112. /**
  113. * 返回记录的游标
  114. *
  115. * @var int
  116. */
  117. protected $offset = 0;
  118.  
  119. /**
  120. * flags 列表
  121. *
  122. * @var array
  123. */
  124. protected $flags = array();
  125.  
  126. /**
  127. * 操作哪个表
  128. *
  129. * @var string
  130. */
  131. protected $table;
  132.  
  133. /**
  134. * 表.列 和 last-insert-id 映射
  135. *
  136. * @var array
  137. */
  138. protected $last_insert_id_names = array();
  139.  
  140. /**
  141. * INSERT 或者 UPDATE 的列
  142. *
  143. * @param array
  144. */
  145. protected $col_values;
  146.  
  147. /**
  148. * 返回的列
  149. *
  150. * @var array
  151. */
  152. protected $returning = array();
  153.  
  154. /**
  155. * sql 的类型 SELECT INSERT DELETE UPDATE
  156. *
  157. * @var string
  158. */
  159. protected $type = '';
  160.  
  161. /**
  162. * pdo 实例
  163. *
  164. * @var PDO
  165. */
  166. protected $pdo;
  167.  
  168. /**
  169. * PDOStatement 实例
  170. *
  171. * @var \PDOStatement
  172. */
  173. protected $sQuery;
  174.  
  175. /**
  176. * 数据库用户名密码等配置
  177. *
  178. * @var array
  179. */
  180. protected $settings = array();
  181.  
  182. /**
  183. * sql 的参数
  184. *
  185. * @var array
  186. */
  187. protected $parameters = array();
  188.  
  189. /**
  190. * 最后一条直行的 sql
  191. *
  192. * @var string
  193. */
  194. protected $lastSql = '';
  195.  
  196. /**
  197. * 是否执行成功
  198. *
  199. * @var bool
  200. */
  201. protected $success = false;
  202.  
  203. /**
  204. * 选择哪些列
  205. *
  206. * @param string|array $cols
  207. * @return self
  208. */
  209. public function select($cols = '*')
  210. {
  211. $this->type = 'SELECT';
  212. if (!is_array($cols)) {
  213. $cols = explode(',', $cols);
  214. }
  215. $this->cols($cols);
  216. return $this;
  217. }
  218.  
  219. /**
  220. * 从哪个表删除
  221. *
  222. * @param string $table
  223. * @return self
  224. */
  225. public function delete($table)
  226. {
  227. $this->type = 'DELETE';
  228. $this->table = $this->quoteName($table);
  229. $this->fromRaw($this->quoteName($table));
  230. return $this;
  231. }
  232.  
  233. /**
  234. * 更新哪个表
  235. *
  236. * @param string $table
  237. * @return self
  238. */
  239. public function update($table)
  240. {
  241. $this->type = 'UPDATE';
  242. $this->table = $this->quoteName($table);
  243. return $this;
  244. }
  245.  
  246. /**
  247. * 向哪个表插入
  248. *
  249. * @param string $table
  250. * @return self
  251. */
  252. public function insert($table)
  253. {
  254. $this->type = 'INSERT';
  255. $this->table = $this->quoteName($table);
  256. return $this;
  257. }
  258.  
  259. /**
  260. *
  261. * 设置 SQL_CALC_FOUND_ROWS 标记.
  262. *
  263. * @param bool $enable
  264. * @return self
  265. */
  266. public function calcFoundRows($enable = true)
  267. {
  268. $this->setFlag('SQL_CALC_FOUND_ROWS', $enable);
  269. return $this;
  270. }
  271.  
  272. /**
  273. * 设置 SQL_CACHE 标记
  274. *
  275. * @param bool $enable
  276. * @return self
  277. */
  278. public function cache($enable = true)
  279. {
  280. $this->setFlag('SQL_CACHE', $enable);
  281. return $this;
  282. }
  283.  
  284. /**
  285. * 设置 SQL_NO_CACHE 标记
  286. *
  287. * @param bool $enable
  288. * @return self
  289. */
  290. public function noCache($enable = true)
  291. {
  292. $this->setFlag('SQL_NO_CACHE', $enable);
  293. return $this;
  294. }
  295.  
  296. /**
  297. * 设置 STRAIGHT_JOIN 标记.
  298. *
  299. * @param bool $enable
  300. * @return self
  301. */
  302. public function straightJoin($enable = true)
  303. {
  304. $this->setFlag('STRAIGHT_JOIN', $enable);
  305. return $this;
  306. }
  307.  
  308. /**
  309. * 设置 HIGH_PRIORITY 标记
  310. *
  311. * @param bool $enable
  312. * @return self
  313. */
  314. public function highPriority($enable = true)
  315. {
  316. $this->setFlag('HIGH_PRIORITY', $enable);
  317. return $this;
  318. }
  319.  
  320. /**
  321. * 设置 SQL_SMALL_RESULT 标记
  322. *
  323. * @param bool $enable
  324. * @return self
  325. */
  326. public function smallResult($enable = true)
  327. {
  328. $this->setFlag('SQL_SMALL_RESULT', $enable);
  329. return $this;
  330. }
  331.  
  332. /**
  333. * 设置 SQL_BIG_RESULT 标记
  334. *
  335. * @param bool $enable
  336. * @return self
  337. */
  338. public function bigResult($enable = true)
  339. {
  340. $this->setFlag('SQL_BIG_RESULT', $enable);
  341. return $this;
  342. }
  343.  
  344. /**
  345. * 设置 SQL_BUFFER_RESULT 标记
  346. *
  347. * @param bool $enable
  348. * @return self
  349. */
  350. public function bufferResult($enable = true)
  351. {
  352. $this->setFlag('SQL_BUFFER_RESULT', $enable);
  353. return $this;
  354. }
  355.  
  356. /**
  357. * 设置 FOR UPDATE 标记
  358. *
  359. * @param bool $enable
  360. * @return self
  361. */
  362. public function forUpdate($enable = true)
  363. {
  364. $this->for_update = (bool)$enable;
  365. return $this;
  366. }
  367.  
  368. /**
  369. * 设置 DISTINCT 标记
  370. *
  371. * @param bool $enable
  372. * @return self
  373. */
  374. public function distinct($enable = true)
  375. {
  376. $this->setFlag('DISTINCT', $enable);
  377. return $this;
  378. }
  379.  
  380. /**
  381. * 设置 LOW_PRIORITY 标记
  382. *
  383. * @param bool $enable
  384. * @return self
  385. */
  386. public function lowPriority($enable = true)
  387. {
  388. $this->setFlag('LOW_PRIORITY', $enable);
  389. return $this;
  390. }
  391.  
  392. /**
  393. * 设置 IGNORE 标记
  394. *
  395. * @param bool $enable
  396. * @return self
  397. */
  398. public function ignore($enable = true)
  399. {
  400. $this->setFlag('IGNORE', $enable);
  401. return $this;
  402. }
  403.  
  404. /**
  405. * 设置 QUICK 标记
  406. *
  407. * @param bool $enable
  408. * @return self
  409. */
  410. public function quick($enable = true)
  411. {
  412. $this->setFlag('QUICK', $enable);
  413. return $this;
  414. }
  415.  
  416. /**
  417. * 设置 DELAYED 标记
  418. *
  419. * @param bool $enable
  420. * @return self
  421. */
  422. public function delayed($enable = true)
  423. {
  424. $this->setFlag('DELAYED', $enable);
  425. return $this;
  426. }
  427.  
  428. /**
  429. * 序列化
  430. *
  431. * @return string
  432. */
  433. public function __toString()
  434. {
  435. $union = '';
  436. if ($this->union) {
  437. $union = implode(' ', $this->union) . ' ';
  438. }
  439. return $union . $this->build();
  440. }
  441.  
  442. /**
  443. * 设置每页多少条记录
  444. *
  445. * @param int $paging
  446. * @return self
  447. */
  448. public function setPaging($paging)
  449. {
  450. $this->paging = (int)$paging;
  451. return $this;
  452. }
  453.  
  454. /**
  455. * 获取每页多少条记录
  456. *
  457. * @return int
  458. */
  459. public function getPaging()
  460. {
  461. return $this->paging;
  462. }
  463.  
  464. /**
  465. * 获取绑定在占位符上的值
  466. */
  467. public function getBindValues()
  468. {
  469. switch ($this->type) {
  470. case 'SELECT':
  471. return $this->getBindValuesSELECT();
  472. case 'DELETE':
  473. case 'UPDATE':
  474. case 'INSERT':
  475. return $this->getBindValuesCOMMON();
  476. default :
  477. throw new Exception("type err");
  478. }
  479. }
  480.  
  481. /**
  482. * 获取绑定在占位符上的值
  483. *
  484. * @return array
  485. */
  486. public function getBindValuesSELECT()
  487. {
  488. $bind_values = $this->bind_values;
  489. $i = 1;
  490. foreach ($this->bind_where as $val) {
  491. $bind_values[$i] = $val;
  492. $i++;
  493. }
  494. foreach ($this->bind_having as $val) {
  495. $bind_values[$i] = $val;
  496. $i++;
  497. }
  498. return $bind_values;
  499. }
  500.  
  501. /**
  502. *
  503. * SELECT选择哪些列
  504. *
  505. * @param mixed $key
  506. * @param string $val
  507. * @return void
  508. */
  509. protected function addColSELECT($key, $val)
  510. {
  511. if (is_string($key)) {
  512. $this->cols[$val] = $key;
  513. } else {
  514. $this->addColWithAlias($val);
  515. }
  516. }
  517.  
  518. /**
  519. * SELECT 增加选择的列
  520. *
  521. * @param string $spec
  522. */
  523. protected function addColWithAlias($spec)
  524. {
  525. $parts = explode(' ', $spec);
  526. $count = count($parts);
  527. if ($count == 2 && trim($parts[0]) != '' && trim($parts[1]) != '') {
  528. $this->cols[$parts[1]] = $parts[0];
  529. } elseif ($count == 3 && strtoupper($parts[1]) == 'AS') {
  530. $this->cols[$parts[2]] = $parts[0];
  531. } else {
  532. $this->cols[] = trim($spec);
  533. }
  534. }
  535.  
  536. /**
  537. * from 哪个表
  538. *
  539. * @param string $table
  540. * @return self
  541. */
  542. public function from($table)
  543. {
  544. return $this->fromRaw($this->quoteName($table));
  545. }
  546.  
  547. /**
  548. * from的表
  549. *
  550. * @param string $table
  551. * @return self
  552. */
  553. public function fromRaw($table)
  554. {
  555. $this->from[] = array($table);
  556. $this->from_key++;
  557. return $this;
  558. }
  559.  
  560. /**
  561. *
  562. * 子查询
  563. *
  564. * @param string $table
  565. * @param string $name The alias name for the sub-select.
  566. * @return self
  567. */
  568. public function fromSubSelect($table, $name)
  569. {
  570. $this->from[] = array("($table) AS " . $this->quoteName($name));
  571. $this->from_key++;
  572. return $this;
  573. }
  574.  
  575.  
  576. /**
  577. * 增加 join 语句
  578. *
  579. * @param string $table
  580. * @param string $cond
  581. * @param string $type
  582. * @return self
  583. * @throws Exception
  584. */
  585. public function join($table, $cond = null, $type = '')
  586. {
  587. return $this->joinInternal($type, $table, $cond);
  588. }
  589.  
  590. /**
  591. * 增加 join 语句
  592. *
  593. * @param string $join inner, left, natural
  594. * @param string $table
  595. * @param string $cond
  596. * @return self
  597. * @throws Exception
  598. */
  599. protected function joinInternal($join, $table, $cond = null)
  600. {
  601. if (!$this->from) {
  602. throw new Exception('Cannot join() without from()');
  603. }
  604.  
  605. $join = strtoupper(ltrim("$join JOIN"));
  606. $table = $this->quoteName($table);
  607. $cond = $this->fixJoinCondition($cond);
  608. $this->from[$this->from_key][] = rtrim("$join $table $cond");
  609. return $this;
  610. }
  611.  
  612. /**
  613. * quote
  614. *
  615. * @param string $cond
  616. * @return string
  617. *
  618. */
  619. protected function fixJoinCondition($cond)
  620. {
  621. if (!$cond) {
  622. return '';
  623. }
  624.  
  625. $cond = $this->quoteNamesIn($cond);
  626.  
  627. if (strtoupper(substr(ltrim($cond), 0, 3)) == 'ON ') {
  628. return $cond;
  629. }
  630.  
  631. if (strtoupper(substr(ltrim($cond), 0, 6)) == 'USING ') {
  632. return $cond;
  633. }
  634.  
  635. return 'ON ' . $cond;
  636. }
  637.  
  638. /**
  639. * inner join
  640. *
  641. * @param string $table
  642. * @param string $cond
  643. * @return self
  644. * @throws Exception
  645. */
  646. public function innerJoin($table, $cond = null)
  647. {
  648. return $this->joinInternal('INNER', $table, $cond);
  649. }
  650.  
  651. /**
  652. * left join
  653. *
  654. * @param string $table
  655. * @param string $cond
  656. * @return self
  657. * @throws Exception
  658. */
  659. public function leftJoin($table, $cond = null)
  660. {
  661. return $this->joinInternal('LEFT', $table, $cond);
  662. }
  663.  
  664. /**
  665. * right join
  666. *
  667. * @param string $table
  668. * @param string $cond
  669. * @return self
  670. * @throws Exception
  671. */
  672. public function rightJoin($table, $cond = null)
  673. {
  674. return $this->joinInternal('RIGHT', $table, $cond);
  675. }
  676.  
  677. /**
  678. * joinSubSelect
  679. *
  680. * @param string $join inner, left, natural
  681. * @param string $spec
  682. * @param string $name sub-select 的别名
  683. * @param string $cond
  684. * @return self
  685. * @throws Exception
  686. */
  687. public function joinSubSelect($join, $spec, $name, $cond = null)
  688. {
  689. if (!$this->from) {
  690. throw new \Exception('Cannot join() without from() first.');
  691. }
  692.  
  693. $join = strtoupper(ltrim("$join JOIN"));
  694. $name = $this->quoteName($name);
  695. $cond = $this->fixJoinCondition($cond);
  696. $this->from[$this->from_key][] = rtrim("$join ($spec) AS $name $cond");
  697. return $this;
  698. }
  699.  
  700. /**
  701. * group by 语句
  702. *
  703. * @param array $cols
  704. * @return self
  705. */
  706. public function groupBy(array $cols)
  707. {
  708. foreach ($cols as $col) {
  709. $this->group_by[] = $this->quoteNamesIn($col);
  710. }
  711. return $this;
  712. }
  713.  
  714. /**
  715. * having 语句
  716. *
  717. * @param string $cond
  718. * @return self
  719. */
  720. public function having($cond)
  721. {
  722. $this->addClauseCondWithBind('having', 'AND', func_get_args());
  723. return $this;
  724. }
  725.  
  726. /**
  727. * or having 语句
  728. *
  729. * @param string $cond The HAVING condition.
  730. * @return self
  731. */
  732. public function orHaving($cond)
  733. {
  734. $this->addClauseCondWithBind('having', 'OR', func_get_args());
  735. return $this;
  736. }
  737.  
  738. /**
  739. * 设置每页的记录数量
  740. *
  741. * @param int $page
  742. * @return self
  743. */
  744. public function page($page)
  745. {
  746. $this->limit = 0;
  747. $this->offset = 0;
  748.  
  749. $page = (int)$page;
  750. if ($page > 0) {
  751. $this->limit = $this->paging;
  752. $this->offset = $this->paging * ($page - 1);
  753. }
  754. return $this;
  755. }
  756.  
  757. /**
  758. * union
  759. *
  760. * @return self
  761. */
  762. public function union()
  763. {
  764. $this->union[] = $this->build() . ' UNION';
  765. $this->reset();
  766. return $this;
  767. }
  768.  
  769. /**
  770. * unionAll
  771. *
  772. * @return self
  773. */
  774. public function unionAll()
  775. {
  776. $this->union[] = $this->build() . ' UNION ALL';
  777. $this->reset();
  778. return $this;
  779. }
  780.  
  781. /**
  782. * 重置
  783. */
  784. protected function reset()
  785. {
  786. $this->resetFlags();
  787. $this->cols = array();
  788. $this->from = array();
  789. $this->from_key = -1;
  790. $this->where = array();
  791. $this->group_by = array();
  792. $this->having = array();
  793. $this->order_by = array();
  794. $this->limit = 0;
  795. $this->offset = 0;
  796. $this->for_update = false;
  797. }
  798.  
  799. /**
  800. * 清除所有数据
  801. */
  802. protected function resetAll()
  803. {
  804. $this->union = array();
  805. $this->for_update = false;
  806. $this->cols = array();
  807. $this->from = array();
  808. $this->from_key = -1;
  809. $this->group_by = array();
  810. $this->having = array();
  811. $this->bind_having = array();
  812. $this->paging = 10;
  813. $this->bind_values = array();
  814. $this->where = array();
  815. $this->bind_where = array();
  816. $this->order_by = array();
  817. $this->limit = 0;
  818. $this->offset = 0;
  819. $this->flags = array();
  820. $this->table = '';
  821. $this->last_insert_id_names = array();
  822. $this->col_values = array();
  823. $this->returning = array();
  824. $this->parameters = array();
  825. }
  826.  
  827. /**
  828. * 创建 SELECT SQL
  829. *
  830. * @return string
  831. */
  832. protected function buildSELECT()
  833. {
  834. return 'SELECT'
  835. . $this->buildFlags()
  836. . $this->buildCols()
  837. . $this->buildFrom()
  838. . $this->buildWhere()
  839. . $this->buildGroupBy()
  840. . $this->buildHaving()
  841. . $this->buildOrderBy()
  842. . $this->buildLimit()
  843. . $this->buildForUpdate();
  844. }
  845.  
  846. /**
  847. * 创建 DELETE SQL
  848. */
  849. protected function buildDELETE()
  850. {
  851. return 'DELETE'
  852. . $this->buildFlags()
  853. . $this->buildFrom()
  854. . $this->buildWhere()
  855. . $this->buildOrderBy()
  856. . $this->buildLimit()
  857. . $this->buildReturning();
  858. }
  859.  
  860. /**
  861. * 生成 SELECT 列语句
  862. *
  863. * @return string
  864. * @throws Exception
  865. */
  866. protected function buildCols()
  867. {
  868. if (!$this->cols) {
  869. throw new Exception('No columns in the SELECT.');
  870. }
  871.  
  872. $cols = array();
  873. foreach ($this->cols as $key => $val) {
  874. if (is_int($key)) {
  875. $cols[] = $this->quoteNamesIn($val);
  876. } else {
  877. $cols[] = $this->quoteNamesIn("$val AS $key");
  878. }
  879. }
  880.  
  881. return $this->indentCsv($cols);
  882. }
  883.  
  884. /**
  885. * 生成 FROM 语句.
  886. *
  887. * @return string
  888. */
  889. protected function buildFrom()
  890. {
  891. if (!$this->from) {
  892. return '';
  893. }
  894.  
  895. $refs = array();
  896. foreach ($this->from as $from) {
  897. $refs[] = implode(' ', $from);
  898. }
  899. return ' FROM' . $this->indentCsv($refs);
  900. }
  901.  
  902. /**
  903. * 生成 GROUP BY 语句.
  904. *
  905. * @return string
  906. */
  907. protected function buildGroupBy()
  908. {
  909. if (!$this->group_by) {
  910. return '';
  911. }
  912. return ' GROUP BY' . $this->indentCsv($this->group_by);
  913. }
  914.  
  915. /**
  916. * 生成 HAVING 语句.
  917. *
  918. * @return string
  919. */
  920. protected function buildHaving()
  921. {
  922. if (!$this->having) {
  923. return '';
  924. }
  925. return ' HAVING' . $this->indent($this->having);
  926. }
  927.  
  928. /**
  929. * 生成 FOR UPDATE 语句
  930. *
  931. * @return string
  932. */
  933. protected function buildForUpdate()
  934. {
  935. if (!$this->for_update) {
  936. return '';
  937. }
  938. return ' FOR UPDATE';
  939. }
  940.  
  941. /**
  942. * where
  943. *
  944. * @param string|array $cond
  945. * @return self
  946. */
  947. public function where($cond)
  948. {
  949. if (is_array($cond)) {
  950. foreach ($cond as $key => $val) {
  951. if (is_string($key)) {
  952. $this->addWhere('AND', array($key, $val));
  953. } else {
  954. $this->addWhere('AND', array($val));
  955. }
  956. }
  957. } else {
  958. $this->addWhere('AND', func_get_args());
  959. }
  960. return $this;
  961. }
  962.  
  963. /**
  964. * or where
  965. *
  966. * @param string|array $cond
  967. * @return self
  968. */
  969. public function orWhere($cond)
  970. {
  971. if (is_array($cond)) {
  972. foreach ($cond as $key => $val) {
  973. if (is_string($key)) {
  974. $this->addWhere('OR', array($key, $val));
  975. } else {
  976. $this->addWhere('OR', array($val));
  977. }
  978. }
  979. } else {
  980. $this->addWhere('OR', func_get_args());
  981. }
  982. return $this;
  983. }
  984.  
  985. /**
  986. * limit
  987. *
  988. * @param int $limit
  989. * @return self
  990. */
  991. public function limit($limit)
  992. {
  993. $this->limit = (int)$limit;
  994. return $this;
  995. }
  996.  
  997. /**
  998. * limit offset
  999. *
  1000. * @param int $offset
  1001. * @return self
  1002. */
  1003. public function offset($offset)
  1004. {
  1005. $this->offset = (int)$offset;
  1006. return $this;
  1007. }
  1008.  
  1009. /**
  1010. * orderby.
  1011. *
  1012. * @param array $cols
  1013. * @return self
  1014. */
  1015. public function orderBy(array $cols)
  1016. {
  1017. return $this->addOrderBy($cols);
  1018. }
  1019.  
  1020. /**
  1021. * order by ASC OR DESC
  1022. *
  1023. * @param array $cols
  1024. * @param bool $order_asc
  1025. * @return self
  1026. */
  1027. public function orderByASC(array $cols, $order_asc = true)
  1028. {
  1029. $this->order_asc = $order_asc;
  1030. return $this->addOrderBy($cols);
  1031. }
  1032.  
  1033. /**
  1034. * order by DESC
  1035. *
  1036. * @param array $cols
  1037. * @return self
  1038. */
  1039. public function orderByDESC(array $cols)
  1040. {
  1041. $this->order_asc = false;
  1042. return $this->addOrderBy($cols);
  1043. }
  1044.  
  1045. // -------------abstractquery----------
  1046. /**
  1047. * 返回逗号分隔的字符串
  1048. *
  1049. * @param array $list
  1050. * @return string
  1051. */
  1052. protected function indentCsv(array $list)
  1053. {
  1054. return ' ' . implode(',', $list);
  1055. }
  1056.  
  1057. /**
  1058. * 返回空格分隔的字符串
  1059. *
  1060. * @param array $list
  1061. * @return string
  1062. */
  1063. protected function indent(array $list)
  1064. {
  1065. return ' ' . implode(' ', $list);
  1066. }
  1067.  
  1068. /**
  1069. * 批量为占位符绑定值
  1070. *
  1071. * @param array $bind_values
  1072. * @return self
  1073. *
  1074. */
  1075. public function bindValues(array $bind_values)
  1076. {
  1077. foreach ($bind_values as $key => $val) {
  1078. $this->bindValue($key, $val);
  1079. }
  1080. return $this;
  1081. }
  1082.  
  1083. /**
  1084. * 单个为占位符绑定值
  1085. *
  1086. * @param string $name
  1087. * @param mixed $value
  1088. * @return self
  1089. */
  1090. public function bindValue($name, $value)
  1091. {
  1092. $this->bind_values[$name] = $value;
  1093. return $this;
  1094. }
  1095.  
  1096. /**
  1097. * 生成 flag
  1098. *
  1099. * @return string
  1100. */
  1101. protected function buildFlags()
  1102. {
  1103. if (!$this->flags) {
  1104. return '';
  1105. }
  1106. return ' ' . implode(' ', array_keys($this->flags));
  1107. }
  1108.  
  1109. /**
  1110. * 设置 flag.
  1111. *
  1112. * @param string $flag
  1113. * @param bool $enable
  1114. */
  1115. protected function setFlag($flag, $enable = true)
  1116. {
  1117. if ($enable) {
  1118. $this->flags[$flag] = true;
  1119. } else {
  1120. unset($this->flags[$flag]);
  1121. }
  1122. }
  1123.  
  1124. /**
  1125. * 重置 flag
  1126. */
  1127. protected function resetFlags()
  1128. {
  1129. $this->flags = array();
  1130. }
  1131.  
  1132. /**
  1133. *
  1134. * 添加 where 语句
  1135. *
  1136. * @param string $andor 'AND' or 'OR
  1137. * @param array $conditions
  1138. * @return self
  1139. *
  1140. */
  1141. protected function addWhere($andor, $conditions)
  1142. {
  1143. $this->addClauseCondWithBind('where', $andor, $conditions);
  1144. return $this;
  1145. }
  1146.  
  1147. /**
  1148. * 添加条件和绑定值
  1149. *
  1150. * @param string $clause where 、having等
  1151. * @param string $andor AND、OR等
  1152. * @param array $conditions
  1153. */
  1154. protected function addClauseCondWithBind($clause, $andor, $conditions)
  1155. {
  1156. $cond = array_shift($conditions);
  1157. $cond = $this->quoteNamesIn($cond);
  1158.  
  1159. $bind =& $this->{"bind_{$clause}"};
  1160. foreach ($conditions as $value) {
  1161. $bind[] = $value;
  1162. }
  1163.  
  1164. $clause =& $this->$clause;
  1165. if ($clause) {
  1166. $clause[] = "$andor $cond";
  1167. } else {
  1168. $clause[] = $cond;
  1169. }
  1170. }
  1171.  
  1172. /**
  1173. * 生成 where 语句
  1174. *
  1175. * @return string
  1176. */
  1177. protected function buildWhere()
  1178. {
  1179. if (!$this->where) {
  1180. return '';
  1181. }
  1182. return ' WHERE' . $this->indent($this->where);
  1183. }
  1184.  
  1185. /**
  1186. * 增加 order by
  1187. *
  1188. * @param array $spec The columns and direction to order by.
  1189. * @return self
  1190. */
  1191. protected function addOrderBy(array $spec)
  1192. {
  1193. foreach ($spec as $col) {
  1194. $this->order_by[] = $this->quoteNamesIn($col);
  1195. }
  1196. return $this;
  1197. }
  1198.  
  1199. /**
  1200. * 生成 order by 语句
  1201. *
  1202. * @return string
  1203. */
  1204. protected function buildOrderBy()
  1205. {
  1206. if (!$this->order_by) {
  1207. return '';
  1208. }
  1209.  
  1210. if ($this->order_asc) {
  1211. return ' ORDER BY' . $this->indentCsv($this->order_by) . ' ASC';
  1212. } else {
  1213. return ' ORDER BY' . $this->indentCsv($this->order_by) . ' DESC';
  1214. }
  1215. }
  1216.  
  1217. /**
  1218. * 生成 limit 语句
  1219. *
  1220. * @return string
  1221. */
  1222. protected function buildLimit()
  1223. {
  1224. $has_limit = $this->type == 'DELETE' || $this->type == 'UPDATE';
  1225. $has_offset = $this->type == 'SELECT';
  1226.  
  1227. if ($has_offset && $this->limit) {
  1228. $clause = " LIMIT {$this->limit}";
  1229. if ($this->offset) {
  1230. $clause .= " OFFSET {$this->offset}";
  1231. }
  1232. return $clause;
  1233. } elseif ($has_limit && $this->limit) {
  1234. return " LIMIT {$this->limit}";
  1235. }
  1236. return '';
  1237. }
  1238.  
  1239. /**
  1240. * Quotes
  1241. *
  1242. * @param string $spec
  1243. * @return string|array
  1244. */
  1245. public function quoteName($spec)
  1246. {
  1247. $spec = trim($spec);
  1248. $seps = array(' AS ', ' ', '.');
  1249. foreach ($seps as $sep) {
  1250. $pos = strripos($spec, $sep);
  1251. if ($pos) {
  1252. return $this->quoteNameWithSeparator($spec, $sep, $pos);
  1253. }
  1254. }
  1255. return $this->replaceName($spec);
  1256. }
  1257.  
  1258. /**
  1259. * 指定分隔符的 Quotes
  1260. *
  1261. * @param string $spec
  1262. * @param string $sep
  1263. * @param int $pos
  1264. * @return string
  1265. */
  1266. protected function quoteNameWithSeparator($spec, $sep, $pos)
  1267. {
  1268. $len = strlen($sep);
  1269. $part1 = $this->quoteName(substr($spec, 0, $pos));
  1270. $part2 = $this->replaceName(substr($spec, $pos + $len));
  1271. return "{$part1}{$sep}{$part2}";
  1272. }
  1273.  
  1274. /**
  1275. * Quotes "table.col" 格式的字符串
  1276. *
  1277. * @param string $text
  1278. * @return string|array
  1279. */
  1280. public function quoteNamesIn($text)
  1281. {
  1282. $list = $this->getListForQuoteNamesIn($text);
  1283. $last = count($list) - 1;
  1284. $text = null;
  1285. foreach ($list as $key => $val) {
  1286. if (($key + 1) % 3) {
  1287. $text .= $this->quoteNamesInLoop($val, $key == $last);
  1288. }
  1289. }
  1290. return $text;
  1291. }
  1292.  
  1293. /**
  1294. * 返回 quote 元素列表
  1295. *
  1296. * @param string $text
  1297. * @return array
  1298. */
  1299. protected function getListForQuoteNamesIn($text)
  1300. {
  1301. $apos = "'";
  1302. $quot = '"';
  1303. return preg_split(
  1304. "/(($apos+|$quot+|\\$apos+|\\$quot+).*?\\2)/",
  1305. $text,
  1306. -1,
  1307. PREG_SPLIT_DELIM_CAPTURE
  1308. );
  1309. }
  1310.  
  1311. /**
  1312. * 循环 quote
  1313. *
  1314. * @param string $val
  1315. * @param bool $is_last
  1316. * @return string
  1317. */
  1318. protected function quoteNamesInLoop($val, $is_last)
  1319. {
  1320. if ($is_last) {
  1321. return $this->replaceNamesAndAliasIn($val);
  1322. }
  1323. return $this->replaceNamesIn($val);
  1324. }
  1325.  
  1326. /**
  1327. * 替换成别名
  1328. *
  1329. * @param string $val
  1330. * @return string
  1331. */
  1332. protected function replaceNamesAndAliasIn($val)
  1333. {
  1334. $quoted = $this->replaceNamesIn($val);
  1335. $pos = strripos($quoted, ' AS ');
  1336. if ($pos !== false) {
  1337. $bracket = strripos($quoted, ')');
  1338. if ($bracket === false) {
  1339. $alias = $this->replaceName(substr($quoted, $pos + 4));
  1340. $quoted = substr($quoted, 0, $pos) . " AS $alias";
  1341. }
  1342. }
  1343. return $quoted;
  1344. }
  1345.  
  1346. /**
  1347. * Quotes name
  1348. *
  1349. * @param string $name
  1350. * @return string
  1351. */
  1352. protected function replaceName($name)
  1353. {
  1354. $name = trim($name);
  1355. if ($name == '*') {
  1356. return $name;
  1357. }
  1358. return '`' . $name . '`';
  1359. }
  1360.  
  1361. /**
  1362. * Quotes
  1363. *
  1364. * @param string $text
  1365. * @return string|array
  1366. */
  1367. protected function replaceNamesIn($text)
  1368. {
  1369. $is_string_literal = strpos($text, "'") !== false
  1370. || strpos($text, '"') !== false;
  1371. if ($is_string_literal) {
  1372. return $text;
  1373. }
  1374.  
  1375. $word = '[a-z_][a-z0-9_]*';
  1376.  
  1377. $find = "/(\\b)($word)\\.($word)(\\b)/i";
  1378.  
  1379. $repl = '$1`$2`.`$3`$4';
  1380.  
  1381. $text = preg_replace($find, $repl, $text);
  1382.  
  1383. return $text;
  1384. }
  1385.  
  1386. // ---------- insert --------------
  1387. /**
  1388. * 设置 `table.column` 与 last-insert-id 的映射
  1389. *
  1390. * @param array $last_insert_id_names
  1391. */
  1392. public function setLastInsertIdNames(array $last_insert_id_names)
  1393. {
  1394. $this->last_insert_id_names = $last_insert_id_names;
  1395. }
  1396.  
  1397. /**
  1398. * insert into.
  1399. *
  1400. * @param string $table
  1401. * @return self
  1402. */
  1403. public function into($table)
  1404. {
  1405. $this->table = $this->quoteName($table);
  1406. return $this;
  1407. }
  1408.  
  1409. /**
  1410. * 生成 INSERT 语句
  1411. *
  1412. * @return string
  1413. */
  1414. protected function buildINSERT()
  1415. {
  1416. return 'INSERT'
  1417. . $this->buildFlags()
  1418. . $this->buildInto()
  1419. . $this->buildValuesForInsert()
  1420. . $this->buildReturning();
  1421. }
  1422.  
  1423. /**
  1424. * 生成 INTO 语句
  1425. *
  1426. * @return string
  1427. */
  1428. protected function buildInto()
  1429. {
  1430. return " INTO " . $this->table;
  1431. }
  1432.  
  1433. /**
  1434. * PDO::lastInsertId()
  1435. *
  1436. * @param string $col
  1437. * @return mixed
  1438. */
  1439. public function getLastInsertIdName($col)
  1440. {
  1441. $key = str_replace('`', '', $this->table) . '.' . $col;
  1442. if (isset($this->last_insert_id_names[$key])) {
  1443. return $this->last_insert_id_names[$key];
  1444. }
  1445.  
  1446. return null;
  1447. }
  1448.  
  1449. /**
  1450. * 设置一列,如果有第二各参数,则把第二个参数绑定在占位符上
  1451. *
  1452. * @param string $col
  1453. * @return self
  1454. */
  1455. public function col($col)
  1456. {
  1457. return call_user_func_array(array($this, 'addCol'), func_get_args());
  1458. }
  1459.  
  1460. /**
  1461. * 设置多列
  1462. *
  1463. * @param array $cols
  1464. * @return self
  1465. */
  1466. public function cols(array $cols)
  1467. {
  1468. if ($this->type == 'SELECT') {
  1469. foreach ($cols as $key => $val) {
  1470. $this->addColSELECT($key, $val);
  1471. }
  1472. return $this;
  1473. }
  1474. return $this->addCols($cols);
  1475. }
  1476.  
  1477. /**
  1478. * 直接设置列的值
  1479. *
  1480. * @param string $col
  1481. * @param string $value
  1482. * @return self
  1483. */
  1484. public function set($col, $value)
  1485. {
  1486. return $this->setCol($col, $value);
  1487. }
  1488.  
  1489. /**
  1490. * 为 INSERT 语句绑定值
  1491. *
  1492. * @return string
  1493. */
  1494. protected function buildValuesForInsert()
  1495. {
  1496. return ' (' . $this->indentCsv(array_keys($this->col_values)) . ') VALUES (' .
  1497. $this->indentCsv(array_values($this->col_values)) . ')';
  1498. }
  1499.  
  1500. // ------update-------
  1501. /**
  1502. * 更新哪个表
  1503. *
  1504. * @param string $table
  1505. * @return self
  1506. */
  1507. public function table($table)
  1508. {
  1509. $this->table = $this->quoteName($table);
  1510. return $this;
  1511. }
  1512.  
  1513. /**
  1514. * 生成完整 SQL 语句
  1515. *
  1516. * @return string
  1517. * @throws Exception
  1518. */
  1519. protected function build()
  1520. {
  1521. switch ($this->type) {
  1522. case 'DELETE':
  1523. return $this->buildDELETE();
  1524. case 'INSERT':
  1525. return $this->buildINSERT();
  1526. case 'UPDATE':
  1527. return $this->buildUPDATE();
  1528. case 'SELECT':
  1529. return $this->buildSELECT();
  1530. }
  1531. throw new Exception("type empty");
  1532. }
  1533.  
  1534. /**
  1535. * 生成更新的 SQL 语句
  1536. */
  1537. protected function buildUPDATE()
  1538. {
  1539. return 'UPDATE'
  1540. . $this->buildFlags()
  1541. . $this->buildTable()
  1542. . $this->buildValuesForUpdate()
  1543. . $this->buildWhere()
  1544. . $this->buildOrderBy()
  1545. . $this->buildLimit()
  1546. . $this->buildReturning();
  1547. }
  1548.  
  1549. /**
  1550. * 哪个表
  1551. *
  1552. * @return string
  1553. */
  1554. protected function buildTable()
  1555. {
  1556. return " {$this->table}";
  1557. }
  1558.  
  1559. /**
  1560. * 为更新语句绑定值
  1561. *
  1562. * @return string
  1563. */
  1564. protected function buildValuesForUpdate()
  1565. {
  1566. $values = array();
  1567. foreach ($this->col_values as $col => $value) {
  1568. $values[] = "{$col} = {$value}";
  1569. }
  1570. return ' SET' . $this->indentCsv($values);
  1571. }
  1572.  
  1573. // ----------Dml---------------
  1574. /**
  1575. * 获取绑定的值
  1576. *
  1577. * @return array
  1578. */
  1579. public function getBindValuesCOMMON()
  1580. {
  1581. $bind_values = $this->bind_values;
  1582. $i = 1;
  1583. foreach ($this->bind_where as $val) {
  1584. $bind_values[$i] = $val;
  1585. $i++;
  1586. }
  1587. return $bind_values;
  1588. }
  1589.  
  1590. /**
  1591. * 设置列
  1592. *
  1593. * @param string $col
  1594. * @return self
  1595. */
  1596. protected function addCol($col)
  1597. {
  1598. $key = $this->quoteName($col);
  1599. $this->col_values[$key] = ":$col";
  1600. $args = func_get_args();
  1601. if (count($args) > 1) {
  1602. $this->bindValue($col, $args[1]);
  1603. }
  1604. return $this;
  1605. }
  1606.  
  1607. /**
  1608. * 设置多个列
  1609. *
  1610. * @param array $cols
  1611. * @return self
  1612. */
  1613. protected function addCols(array $cols)
  1614. {
  1615. foreach ($cols as $key => $val) {
  1616. if (is_int($key)) {
  1617. $this->addCol($val);
  1618. } else {
  1619. $this->addCol($key, $val);
  1620. }
  1621. }
  1622. return $this;
  1623. }
  1624.  
  1625. /**
  1626. * 设置单列的值
  1627. *
  1628. * @param string $col .
  1629. * @param string $value
  1630. * @return self
  1631. */
  1632. protected function setCol($col, $value)
  1633. {
  1634. if ($value === null) {
  1635. $value = 'NULL';
  1636. }
  1637.  
  1638. $key = $this->quoteName($col);
  1639. $value = $this->quoteNamesIn($value);
  1640. $this->col_values[$key] = $value;
  1641. return $this;
  1642. }
  1643.  
  1644. /**
  1645. * 增加返回的列
  1646. *
  1647. * @param array $cols
  1648. * @return self
  1649. *
  1650. */
  1651. protected function addReturning(array $cols)
  1652. {
  1653. foreach ($cols as $col) {
  1654. $this->returning[] = $this->quoteNamesIn($col);
  1655. }
  1656. return $this;
  1657. }
  1658.  
  1659. /**
  1660. * 生成 RETURNING 语句
  1661. *
  1662. * @return string
  1663. */
  1664. protected function buildReturning()
  1665. {
  1666. if (!$this->returning) {
  1667. return '';
  1668. }
  1669. return ' RETURNING' . $this->indentCsv($this->returning);
  1670. }
  1671.  
  1672. /**
  1673. * 构造函数
  1674. *
  1675. * @param string $host
  1676. * @param int $port
  1677. * @param string $user
  1678. * @param string $password
  1679. * @param string $db_name
  1680. * @param string $charset
  1681. */
  1682. public function __construct($host, $port, $user, $password, $db_name, $charset = 'utf8')
  1683. {
  1684. $this->settings = array(
  1685. 'host' => $host,
  1686. 'port' => $port,
  1687. 'user' => $user,
  1688. 'password' => $password,
  1689. 'dbname' => $db_name,
  1690. 'charset' => $charset,
  1691. );
  1692. $this->connect();
  1693. }
  1694.  
  1695. /**
  1696. * 创建 PDO 实例
  1697. */
  1698. protected function connect()
  1699. {
  1700. $dsn = 'mysql:dbname=' . $this->settings["dbname"] . ';host=' .
  1701. $this->settings["host"] . ';port=' . $this->settings['port'];
  1702. $this->pdo = new PDO($dsn, $this->settings["user"], $this->settings["password"],
  1703. array(
  1704. PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES ' . (!empty($this->settings['charset']) ?
  1705. $this->settings['charset'] : 'utf8')
  1706. ));
  1707. $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1708. $this->pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, false);
  1709. $this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  1710. }
  1711.  
  1712. /**
  1713. * 关闭连接
  1714. */
  1715. public function closeConnection()
  1716. {
  1717. $this->pdo = null;
  1718. }
  1719.  
  1720. /**
  1721. * 执行
  1722. *
  1723. * @param string $query
  1724. * @param string $parameters
  1725. * @throws PDOException
  1726. */
  1727. protected function execute($query, $parameters = "")
  1728. {
  1729. try {
  1730. if (is_null($this->pdo)) {
  1731. $this->connect();
  1732. }
  1733. $this->sQuery = @$this->pdo->prepare($query);
  1734. $this->bindMore($parameters);
  1735. if (!empty($this->parameters)) {
  1736. foreach ($this->parameters as $param) {
  1737. $this->sQuery->bindParam($param[0], $param[1]);
  1738. }
  1739. }
  1740. $this->success = $this->sQuery->execute();
  1741. } catch (PDOException $e) {
  1742. // 服务端断开时重连一次
  1743. if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
  1744. $this->closeConnection();
  1745. $this->connect();
  1746.  
  1747. try {
  1748. $this->sQuery = $this->pdo->prepare($query);
  1749. $this->bindMore($parameters);
  1750. if (!empty($this->parameters)) {
  1751. foreach ($this->parameters as $param) {
  1752. $this->sQuery->bindParam($param[0], $param[1]);
  1753. }
  1754. }
  1755. $this->success = $this->sQuery->execute();
  1756. } catch (PDOException $ex) {
  1757. $this->rollBackTrans();
  1758. throw $ex;
  1759. }
  1760. } else {
  1761. $this->rollBackTrans();
  1762. $msg = $e->getMessage();
  1763. $err_msg = "SQL:".$this->lastSQL()." ".$msg;
  1764. $exception = new \PDOException($err_msg, (int)$e->getCode());
  1765. throw $exception;
  1766. }
  1767. }
  1768. $this->parameters = array();
  1769. }
  1770.  
  1771. /**
  1772. * 绑定
  1773. *
  1774. * @param string $para
  1775. * @param string $value
  1776. */
  1777. public function bind($para, $value)
  1778. {
  1779. if (is_string($para)) {
  1780. $this->parameters[sizeof($this->parameters)] = array(":" . $para, $value);
  1781. } else {
  1782. $this->parameters[sizeof($this->parameters)] = array($para, $value);
  1783. }
  1784. }
  1785.  
  1786. /**
  1787. * 绑定多个
  1788. *
  1789. * @param array $parray
  1790. */
  1791. public function bindMore($parray)
  1792. {
  1793. if (empty($this->parameters) && is_array($parray)) {
  1794. $columns = array_keys($parray);
  1795. foreach ($columns as $i => &$column) {
  1796. $this->bind($column, $parray[$column]);
  1797. }
  1798. }
  1799. }
  1800.  
  1801. /**
  1802. * 执行 SQL
  1803. *
  1804. * @param string $query
  1805. * @param array $params
  1806. * @param int $fetchmode
  1807. * @return mixed
  1808. */
  1809. public function query($query = '', $params = null, $fetchmode = PDO::FETCH_ASSOC)
  1810. {
  1811. $query = trim($query);
  1812. if (empty($query)) {
  1813. $query = $this->build();
  1814. if (!$params) {
  1815. $params = $this->getBindValues();
  1816. }
  1817. }
  1818.  
  1819. $this->resetAll();
  1820. $this->lastSql = $query;
  1821.  
  1822. $this->execute($query, $params);
  1823.  
  1824. $rawStatement = explode(" ", $query);
  1825.  
  1826. $statement = strtolower(trim($rawStatement[0]));
  1827. if ($statement === 'select' || $statement === 'show') {
  1828. return $this->sQuery->fetchAll($fetchmode);
  1829. } elseif ($statement === 'update' || $statement === 'delete' || $statement === 'replace') {
  1830. return $this->sQuery->rowCount();
  1831. } elseif ($statement === 'insert') {
  1832. if ($this->sQuery->rowCount() > 0) {
  1833. return $this->lastInsertId();
  1834. }
  1835. } else {
  1836. return null;
  1837. }
  1838.  
  1839. return null;
  1840. }
  1841.  
  1842. /**
  1843. * 返回一列
  1844. *
  1845. * @param string $query
  1846. * @param array $params
  1847. * @return array
  1848. */
  1849. public function column($query = '', $params = null)
  1850. {
  1851. $query = trim($query);
  1852. if (empty($query)) {
  1853. $query = $this->build();
  1854. if (!$params) {
  1855. $params = $this->getBindValues();
  1856. }
  1857. }
  1858.  
  1859. $this->resetAll();
  1860. $this->lastSql = $query;
  1861.  
  1862. $this->execute($query, $params);
  1863. $columns = $this->sQuery->fetchAll(PDO::FETCH_NUM);
  1864. $column = null;
  1865. foreach ($columns as $cells) {
  1866. $column[] = $cells[0];
  1867. }
  1868. return $column;
  1869. }
  1870.  
  1871. /**
  1872. * 返回一行
  1873. *
  1874. * @param string $query
  1875. * @param array $params
  1876. * @param int $fetchmode
  1877. * @return array
  1878. */
  1879. public function row($query = '', $params = null, $fetchmode = PDO::FETCH_ASSOC)
  1880. {
  1881. $query = trim($query);
  1882. if (empty($query)) {
  1883. $query = $this->build();
  1884. if (!$params) {
  1885. $params = $this->getBindValues();
  1886. }
  1887. }
  1888.  
  1889. $this->resetAll();
  1890. $this->lastSql = $query;
  1891.  
  1892. $this->execute($query, $params);
  1893. return $this->sQuery->fetch($fetchmode);
  1894. }
  1895.  
  1896. /**
  1897. * 返回单个值
  1898. *
  1899. * @param string $query
  1900. * @param array $params
  1901. * @return string
  1902. */
  1903. public function single($query = '', $params = null)
  1904. {
  1905. $query = trim($query);
  1906. if (empty($query)) {
  1907. $query = $this->build();
  1908. if (!$params) {
  1909. $params = $this->getBindValues();
  1910. }
  1911. }
  1912.  
  1913. $this->resetAll();
  1914. $this->lastSql = $query;
  1915.  
  1916. $this->execute($query, $params);
  1917. return $this->sQuery->fetchColumn();
  1918. }
  1919.  
  1920. /**
  1921. * 返回 lastInsertId
  1922. *
  1923. * @return string
  1924. */
  1925. public function lastInsertId()
  1926. {
  1927. return $this->pdo->lastInsertId();
  1928. }
  1929.  
  1930. /**
  1931. * 返回最后一条执行的 sql
  1932. *
  1933. * @return string
  1934. */
  1935. public function lastSQL()
  1936. {
  1937. return $this->lastSql;
  1938. }
  1939.  
  1940. /**
  1941. * 开始事务
  1942. */
  1943. public function beginTrans()
  1944. {
  1945. try {
  1946. if (is_null($this->pdo)) {
  1947. $this->connect();
  1948. }
  1949. return $this->pdo->beginTransaction();
  1950. } catch (PDOException $e) {
  1951. // 服务端断开时重连一次
  1952. if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
  1953. $this->closeConnection();
  1954. $this->connect();
  1955. return $this->pdo->beginTransaction();
  1956. } else {
  1957. throw $e;
  1958. }
  1959. }
  1960. }
  1961.  
  1962. /**
  1963. * 提交事务
  1964. */
  1965. public function commitTrans()
  1966. {
  1967. return $this->pdo->commit();
  1968. }
  1969.  
  1970. /**
  1971. * 事务回滚
  1972. */
  1973. public function rollBackTrans()
  1974. {
  1975. if ($this->pdo->inTransaction()) {
  1976. return $this->pdo->rollBack();
  1977. }
  1978. return true;
  1979. }
  1980. }

链式操作的关键是在做完操作后要return $this。return $this表示方法结束后,返回的是当前对象,它可以实现链式操作。

原文地址:

以上就是php链式操作mysql数据库(封装类带使用示例)的详细内容,更多关于php链式操作mysql数据库(封装类带使用示例)的资料请关注九品源码其它相关文章!