Blogger Information
Blog 15
fans 0
comment 0
visits 7771
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
数据库查询构造器
ッ小眼睛っ
Original
696 people have browsed it

作业问题:

代码:

  1. <?php
  2. class Query
  3. {
  4. //创建类的唯一实例
  5. private static $db;
  6. protected $table;
  7. protected $field;
  8. protected $limit;
  9. private function __construct()
  10. {
  11. }
  12. static function connect($dsn,$username,$pwd)
  13. {
  14. if(is_null(static::$db)){
  15. static::$db = new PDO($dsn,$username,$pwd);
  16. }
  17. //返回query实例
  18. return new static();
  19. }
  20. public function table($table)
  21. {
  22. $this->table = $table;
  23. // echo $this->table;
  24. return $this;
  25. }
  26. public function field($field)
  27. {
  28. $this->field = $field;
  29. // echo $this->field;
  30. return $this;
  31. }
  32. public function limit($limit)
  33. {
  34. $this->limit = $limit;
  35. return $this;
  36. }
  37. public function getSql()
  38. {
  39. return 'SELECT '.$this->field.' FROM '.$this->table.' LIMIT '.$this->limit;
  40. // return sprintf('SELECT %s FROM %s LIMIT %d',$this->field,$this->table,$this->limit);
  41. }
  42. public function select(){
  43. return static::$db->query($this->getSql())->fetchALL(PDO::FETCH_ASSOC);
  44. }
  45. }
  46. class Db
  47. {
  48. static function __callStatic($method, $arygs)
  49. {
  50. $dsn = 'mysql:host=localhost;dbname=test_db';
  51. $username = 'test_db';
  52. $pwd = '123456';
  53. //获取委托实例
  54. $query = Query::connect($dsn,$username,$pwd);
  55. return call_user_func([$query,$method],...$arygs);
  56. }
  57. }
  58. //$res = Db::table('t_user')
  59. // ->field('name')
  60. // ->limit(1)
  61. // ->select();
  62. //
  63. //print_r($res);
  64. print_r(Db::filed('nihao'));
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post