php链式操作mysql数据库的方法是什么

后端开发   发布日期:2023年07月07日   浏览次数:625

本篇内容介绍了“php链式操作mysql数据库的方法是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

封装类常用操作使用示例

  1. // 初始化db连接
  2. $db = new WorkermanMySQLConnection('host', 'port', 'user', 'password', 'db_name');
  3. // 获取所有数据
  4. $db->select('ID,Sex')->from('Persons')->where('sex= :sex AND ID = :id')->bindValues(array('sex'=>'M', 'id' => 1))->query();
  5. //等价于
  6. $db->select('ID,Sex')->from('Persons')->where("sex= 'M' AND ID = 1")->query();
  7. //等价于
  8. $db->query("SELECT ID,Sex FROM `Persons` WHERE sex='M' AND ID = 1");
  9. // 获取一行数据
  10. $db->select('ID,Sex')->from('Persons')->where('sex= :sex')->bindValues(array('sex'=>'M'))->row();
  11. //等价于
  12. $db->select('ID,Sex')->from('Persons')->where("sex= 'M' ")->row();
  13. //等价于
  14. $db->row("SELECT ID,Sex FROM `Persons` WHERE sex='M'");
  15. // 获取一列数据
  16. $db->select('ID')->from('Persons')->where('sex= :sex')->bindValues(array('sex'=>'M'))->column();
  17. //等价于
  18. $db->select('ID')->from('Persons')->where("sex= 'F' ")->column();
  19. //等价于
  20. $db->column("SELECT `ID` FROM `Persons` WHERE sex='M'");
  21. // 获取单个值
  22. $db->select('ID')->from('Persons')->where('sex= :sex')->bindValues(array('sex'=>'M'))->single();
  23. //等价于
  24. $db->select('ID')->from('Persons')->where("sex= 'F' ")->single();
  25. //等价于
  26. $db->single("SELECT ID FROM `Persons` WHERE sex='M'");
  27. // 复杂查询
  28. $db->select('*')->from('table1')->innerJoin('table2','table1.uid = table2.uid')->where('age > :age')->groupBy(array('aid'))->having('foo="foo"')->orderByASC/*orderByDESC*/(array('did'))
  29. ->limit(10)->offset(20)->bindValues(array('age' => 13));
  30. // 等价于
  31. $db->query('SELECT * FROM `table1` INNER JOIN `table2` ON `table1`.`uid` = `table2`.`uid`
  32. WHERE age > 13 GROUP BY aid HAVING foo="foo" ORDER BY did LIMIT 10 OFFSET 20');
  33. // 插入
  34. $insert_id = $db->insert('Persons')->cols(array(
  35. 'Firstname'=>'abc',
  36. 'Lastname'=>'efg',
  37. 'Sex'=>'M',
  38. 'Age'=>13))->query();
  39. 等价于
  40. $insert_id = $db->query("INSERT INTO `Persons` ( `Firstname`,`Lastname`,`Sex`,`Age`)
  41. VALUES ( 'abc', 'efg', 'M', 13)");
  42. // 更新
  43. $row_count = $db->update('Persons')->cols(array('sex'))->where('ID=1')
  44. ->bindValue('sex', 'F')->query();
  45. // 等价于
  46. $row_count = $db->update('Persons')->cols(array('sex'=>'F'))->where('ID=1')->query();
  47. // 等价于
  48. $row_count = $db->query("UPDATE `Persons` SET `sex` = 'F' WHERE ID=1");
  49. // 删除
  50. $row_count = $db->delete('Persons')->where('ID=9')->query();
  51. // 等价于
  52. $row_count = $db->query("DELETE FROM `Persons` WHERE ID=9");
  53. // 事务
  54. $db->beginTrans();
  55. ....
  56. $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. * @var bool
  18. */
  19. protected $for_update = false;
  20. /**
  21. * 选择的列
  22. *
  23. * @var array
  24. */
  25. protected $cols = array();
  26. /**
  27. * 从哪些表里面 SELECT
  28. *
  29. * @var array
  30. */
  31. protected $from = array();
  32. /**
  33. * $from 当前的 key
  34. *
  35. * @var int
  36. */
  37. protected $from_key = -1;
  38. /**
  39. * GROUP BY 的列
  40. *
  41. * @var array
  42. */
  43. protected $group_by = array();
  44. /**
  45. * HAVING 条件数组.
  46. *
  47. * @var array
  48. */
  49. protected $having = array();
  50. /**
  51. * HAVING 语句中绑定的值.
  52. *
  53. * @var array
  54. */
  55. protected $bind_having = array();
  56. /**
  57. * 每页多少条记录
  58. *
  59. * @var int
  60. */
  61. protected $paging = 10;
  62. /**
  63. * sql 中绑定的值
  64. *
  65. * @var array
  66. */
  67. protected $bind_values = array();
  68. /**
  69. * WHERE 条件.
  70. *
  71. * @var array
  72. */
  73. protected $where = array();
  74. /**
  75. * WHERE 语句绑定的值
  76. *
  77. * @var array
  78. */
  79. protected $bind_where = array();
  80. /**
  81. * ORDER BY 的列
  82. *
  83. * @var array
  84. */
  85. protected $order_by = array();
  86. /**
  87. * ORDER BY 的排序方式,默认为升序
  88. *
  89. * @var bool
  90. */
  91. protected $order_asc = true;
  92. /**
  93. * SELECT 多少记录
  94. *
  95. * @var int
  96. */
  97. protected $limit = 0;
  98. /**
  99. * 返回记录的游标
  100. *
  101. * @var int
  102. */
  103. protected $offset = 0;
  104. /**
  105. * flags 列表
  106. *
  107. * @var array
  108. */
  109. protected $flags = array();
  110. /**
  111. * 操作哪个表
  112. *
  113. * @var string
  114. */
  115. protected $table;
  116. /**
  117. * 表.列 和 last-insert-id 映射
  118. *
  119. * @var array
  120. */
  121. protected $last_insert_id_names = array();
  122. /**
  123. * INSERT 或者 UPDATE 的列
  124. *
  125. * @param array
  126. */
  127. protected $col_values;
  128. /**
  129. * 返回的列
  130. *
  131. * @var array
  132. */
  133. protected $returning = array();
  134. /**
  135. * sql 的类型 SELECT INSERT DELETE UPDATE
  136. *
  137. * @var string
  138. */
  139. protected $type = '';
  140. /**
  141. * pdo 实例
  142. *
  143. * @var PDO
  144. */
  145. protected $pdo;
  146. /**
  147. * PDOStatement 实例
  148. *
  149. * @var PDOStatement
  150. */
  151. protected $sQuery;
  152. /**
  153. * 数据库用户名密码等配置
  154. *
  155. * @var array
  156. */
  157. protected $settings = array();
  158. /**
  159. * sql 的参数
  160. *
  161. * @var array
  162. */
  163. protected $parameters = array();
  164. /**
  165. * 最后一条直行的 sql
  166. *
  167. * @var string
  168. */
  169. protected $lastSql = '';
  170. /**
  171. * 是否执行成功
  172. *
  173. * @var bool
  174. */
  175. protected $success = false;
  176. /**
  177. * 选择哪些列
  178. *
  179. * @param string|array $cols
  180. * @return self
  181. */
  182. public function select($cols = '*')
  183. {
  184. $this->type = 'SELECT';
  185. if (!is_array($cols)) {
  186. $cols = explode(',', $cols);
  187. }
  188. $this->cols($cols);
  189. return $this;
  190. }
  191. /**
  192. * 从哪个表删除
  193. *
  194. * @param string $table
  195. * @return self
  196. */
  197. public function delete($table)
  198. {
  199. $this->type = 'DELETE';
  200. $this->table = $this->quoteName($table);
  201. $this->fromRaw($this->quoteName($table));
  202. return $this;
  203. }
  204. /**
  205. * 更新哪个表
  206. *
  207. * @param string $table
  208. * @return self
  209. */
  210. public function update($table)
  211. {
  212. $this->type = 'UPDATE';
  213. $this->table = $this->quoteName($table);
  214. return $this;
  215. }
  216. /**
  217. * 向哪个表插入
  218. *
  219. * @param string $table
  220. * @return self
  221. */
  222. public function insert($table)
  223. {
  224. $this->type = 'INSERT';
  225. $this->table = $this->quoteName($table);
  226. return $this;
  227. }
  228. /**
  229. *
  230. * 设置 SQL_CALC_FOUND_ROWS 标记.
  231. *
  232. * @param bool $enable
  233. * @return self
  234. */
  235. public function calcFoundRows($enable = true)
  236. {
  237. $this->setFlag('SQL_CALC_FOUND_ROWS', $enable);
  238. return $this;
  239. }
  240. /**
  241. * 设置 SQL_CACHE 标记
  242. *
  243. * @param bool $enable
  244. * @return self
  245. */
  246. public function cache($enable = true)
  247. {
  248. $this->setFlag('SQL_CACHE', $enable);
  249. return $this;
  250. }
  251. /**
  252. * 设置 SQL_NO_CACHE 标记
  253. *
  254. * @param bool $enable
  255. * @return self
  256. */
  257. public function noCache($enable = true)
  258. {
  259. $this->setFlag('SQL_NO_CACHE', $enable);
  260. return $this;
  261. }
  262. /**
  263. * 设置 STRAIGHT_JOIN 标记.
  264. *
  265. * @param bool $enable
  266. * @return self
  267. */
  268. public function straightJoin($enable = true)
  269. {
  270. $this->setFlag('STRAIGHT_JOIN', $enable);
  271. return $this;
  272. }
  273. /**
  274. * 设置 HIGH_PRIORITY 标记
  275. *
  276. * @param bool $enable
  277. * @return self
  278. */
  279. public function highPriority($enable = true)
  280. {
  281. $this->setFlag('HIGH_PRIORITY', $enable);
  282. return $this;
  283. }
  284. /**
  285. * 设置 SQL_SMALL_RESULT 标记
  286. *
  287. * @param bool $enable
  288. * @return self
  289. */
  290. public function smallResult($enable = true)
  291. {
  292. $this->setFlag('SQL_SMALL_RESULT', $enable);
  293. return $this;
  294. }
  295. /**
  296. * 设置 SQL_BIG_RESULT 标记
  297. *
  298. * @param bool $enable
  299. * @return self
  300. */
  301. public function bigResult($enable = true)
  302. {
  303. $this->setFlag('SQL_BIG_RESULT', $enable);
  304. return $this;
  305. }
  306. /**
  307. * 设置 SQL_BUFFER_RESULT 标记
  308. *
  309. * @param bool $enable
  310. * @return self
  311. */
  312. public function bufferResult($enable = true)
  313. {
  314. $this->setFlag('SQL_BUFFER_RESULT', $enable);
  315. return $this;
  316. }
  317. /**
  318. * 设置 FOR UPDATE 标记
  319. *
  320. * @param bool $enable
  321. * @return self
  322. */
  323. public function forUpdate($enable = true)
  324. {
  325. $this->for_update = (bool)$enable;
  326. return $this;
  327. }
  328. /**
  329. * 设置 DISTINCT 标记
  330. *
  331. * @param bool $enable
  332. * @return self
  333. */
  334. public function distinct($enable = true)
  335. {
  336. $this->setFlag('DISTINCT', $enable);
  337. return $this;
  338. }
  339. /**
  340. * 设置 LOW_PRIORITY 标记
  341. *
  342. * @param bool $enable
  343. * @return self
  344. */
  345. public function lowPriority($enable = true)
  346. {
  347. $this->setFlag('LOW_PRIORITY', $enable);
  348. return $this;
  349. }
  350. /**
  351. * 设置 IGNORE 标记
  352. *
  353. * @param bool $enable
  354. * @return self
  355. */
  356. public function ignore($enable = true)
  357. {
  358. $this->setFlag('IGNORE', $enable);
  359. return $this;
  360. }
  361. /**
  362. * 设置 QUICK 标记
  363. *
  364. * @param bool $enable
  365. * @return self
  366. */
  367. public function quick($enable = true)
  368. {
  369. $this->setFlag('QUICK', $enable);
  370. return $this;
  371. }
  372. /**
  373. * 设置 DELAYED 标记
  374. *
  375. * @param bool $enable
  376. * @return self
  377. */
  378. public function delayed($enable = true)
  379. {
  380. $this->setFlag('DELAYED', $enable);
  381. return $this;
  382. }
  383. /**
  384. * 序列化
  385. *
  386. * @return string
  387. */
  388. public function __toString()
  389. {
  390. $union = '';
  391. if ($this->union) {
  392. $union = implode(' ', $this->union) . ' ';
  393. }
  394. return $union . $this->build();
  395. }
  396. /**
  397. * 设置每页多少条记录
  398. *
  399. * @param int $paging
  400. * @return self
  401. */
  402. public function setPaging($paging)
  403. {
  404. $this->paging = (int)$paging;
  405. return $this;
  406. }
  407. /**
  408. * 获取每页多少条记录
  409. *
  410. * @return int
  411. */
  412. public function getPaging()
  413. {
  414. return $this->paging;
  415. }
  416. /**
  417. * 获取绑定在占位符上的值
  418. */
  419. public function getBindValues()
  420. {
  421. switch ($this->type) {
  422. case 'SELECT':
  423. return $this->getBindValuesSELECT();
  424. case 'DELETE':
  425. case 'UPDATE':
  426. case 'INSERT':
  427. return $this->getBindValuesCOMMON();
  428. default :
  429. throw new Exception("type err");
  430. }
  431. }
  432. /**
  433. * 获取绑定在占位符上的值
  434. *
  435. * @return array
  436. */
  437. public function getBindValuesSELECT()
  438. {
  439. $bind_values = $this->bind_values;
  440. $i = 1;
  441. foreach ($this->bind_where as $val) {
  442. $bind_values[$i] = $val;
  443. $i++;
  444. }
  445. foreach ($this->bind_having as $val) {
  446. $bind_values[$i] = $val;
  447. $i++;
  448. }
  449. return $bind_values;
  450. }
  451. /**
  452. *
  453. * SELECT选择哪些列
  454. *
  455. * @param mixed $key
  456. * @param string $val
  457. * @return void
  458. */
  459. protected function addColSELECT($key, $val)
  460. {
  461. if (is_string($key)) {
  462. $this->cols[$val] = $key;
  463. } else {
  464. $this->addColWithAlias($val);
  465. }
  466. }
  467. /**
  468. * SELECT 增加选择的列
  469. *
  470. * @param string $spec
  471. */
  472. protected function addColWithAlias($spec)
  473. {
  474. $parts = explode(' ', $spec);
  475. $count = count($parts);
  476. if ($count == 2 && trim($parts[0]) != '' && trim($parts[1]) != '') {
  477. $this->cols[$parts[1]] = $parts[0];
  478. } elseif ($count == 3 && strtoupper($parts[1]) == 'AS') {
  479. $this->cols[$parts[2]] = $parts[0];
  480. } else {
  481. $this->cols[] = trim($spec);
  482. }
  483. }
  484. /**
  485. * from 哪个表
  486. *
  487. * @param string $table
  488. * @return self
  489. */
  490. public function from($table)
  491. {
  492. return $this->fromRaw($this->quoteName($table));
  493. }
  494. /**
  495. * from的表
  496. *
  497. * @param string $table
  498. * @return self
  499. */
  500. public function fromRaw($table)
  501. {
  502. $this->from[] = array($table);
  503. $this->from_key++;
  504. return $this;
  505. }
  506. /**
  507. *
  508. * 子查询
  509. *
  510. * @param string $table
  511. * @param string $name The alias name for the sub-select.
  512. * @return self
  513. */
  514. public function fromSubSelect($table, $name)
  515. {
  516. $this->from[] = array("($table) AS " . $this->quoteName($name));
  517. $this->from_key++;
  518. return $this;
  519. }
  520. /**
  521. * 增加 join 语句
  522. *
  523. * @param string $table
  524. * @param string $cond
  525. * @param string $type
  526. * @return self
  527. * @throws Exception
  528. */
  529. public function join($table, $cond = null, $type = '')
  530. {
  531. return $this->joinInternal($type, $table, $cond);
  532. }
  533. /**
  534. * 增加 join 语句
  535. *
  536. * @param string $join inner, left, natural
  537. * @param string $table
  538. * @param string $cond
  539. * @return self
  540. * @throws Exception
  541. */
  542. protected function joinInternal($join, $table, $cond = null)
  543. {
  544. if (!$this->from) {
  545. throw new Exception('Cannot join() without from()');
  546. }
  547. $join = strtoupper(ltrim("$join JOIN"));
  548. $table = $this->quoteName($table);
  549. $cond = $this->fixJoinCondition($cond);
  550. $this->from[$this->from_key][] = rtrim("$join $table $cond");
  551. return $this;
  552. }
  553. /**
  554. * quote
  555. *
  556. * @param string $cond
  557. * @return string
  558. *
  559. */
  560. protected function fixJoinCondition($cond)
  561. {
  562. if (!$cond) {
  563. return '';
  564. }
  565. $cond = $this->quoteNamesIn($cond);
  566. if (strtoupper(substr(ltrim($cond), 0, 3)) == 'ON ') {
  567. return $cond;
  568. }
  569. if (strtoupper(substr(ltrim($cond), 0, 6)) == 'USING ') {
  570. return $cond;
  571. }
  572. return 'ON ' . $cond;
  573. }
  574. /**
  575. * inner join
  576. *
  577. * @param string $table
  578. * @param string $cond
  579. * @return self
  580. * @throws Exception
  581. */
  582. public function innerJoin($table, $cond = null)
  583. {
  584. return $this->joinInternal('INNER', $table, $cond);
  585. }
  586. /**
  587. * left join
  588. *
  589. * @param string $table
  590. * @param string $cond
  591. * @return self
  592. * @throws Exception
  593. */
  594. public function leftJoin($table, $cond = null)
  595. {
  596. return $this->joinInternal('LEFT', $table, $cond);
  597. }
  598. /**
  599. * right join
  600. *
  601. * @param string $table
  602. * @param string $cond
  603. * @return self
  604. * @throws Exception
  605. */
  606. public function rightJoin($table, $cond = null)
  607. {
  608. return $this->joinInternal('RIGHT', $table, $cond);
  609. }
  610. /**
  611. * joinSubSelect
  612. *
  613. * @param string $join inner, left, natural
  614. * @param string $spec
  615. * @param string $name sub-select 的别名
  616. * @param string $cond
  617. * @return self
  618. * @throws Exception
  619. */
  620. public function joinSubSelect($join, $spec, $name, $cond = null)
  621. {
  622. if (!$this->from) {
  623. throw new Exception('Cannot join() without from() first.');
  624. }
  625. $join = strtoupper(ltrim("$join JOIN"));
  626. $name = $this->quoteName($name);
  627. $cond = $this->fixJoinCondition($cond);
  628. $this->from[$this->from_key][] = rtrim("$join ($spec) AS $name $cond");
  629. return $this;
  630. }
  631. /**
  632. * group by 语句
  633. *
  634. * @param array $cols
  635. * @return self
  636. */
  637. public function groupBy(array $cols)
  638. {
  639. foreach ($cols as $col) {
  640. $this->group_by[] = $this->quoteNamesIn($col);
  641. }
  642. return $this;
  643. }
  644. /**
  645. * having 语句
  646. *
  647. * @param string $cond
  648. * @return self
  649. */
  650. public function having($cond)
  651. {
  652. $this->addClauseCondWithBind('having', 'AND', func_get_args());
  653. return $this;
  654. }
  655. /**
  656. * or having 语句
  657. *
  658. * @param string $cond The HAVING condition.
  659. * @return self
  660. */
  661. public function orHaving($cond)
  662. {
  663. $this->addClauseCondWithBind('having', 'OR', func_get_args());
  664. return $this;
  665. }
  666. /**
  667. * 设置每页的记录数量
  668. *
  669. * @param int $page
  670. * @return self
  671. */

以上就是php链式操作mysql数据库的方法是什么的详细内容,更多关于php链式操作mysql数据库的方法是什么的资料请关注九品源码其它相关文章!