博客列表 >数据库查询构造器

数据库查询构造器

冰雪琉璃
冰雪琉璃原创
2021年05月15日 17:16:34598浏览

数据库查询构造器

  1. class Query()
  2. {
  3. protected $db;//PDO连接对象
  4. protected $table;
  5. protected $field;
  6. protected $where;
  7. protected $Limit;
  8. protected $select;
  9. protected $toArray;
  10. //连接数据库
  11. private function connect($dsn,$username,$password)
  12. {
  13. $this->db=new PDO($dsn,$username,$password);
  14. }
  15. function __construct($dsn,$username,$password)
  16. {
  17. $this->connect($dsn,$username,$password);
  18. }
  19. //数据表方法$table
  20. public function table($table)
  21. {
  22. $this->table=$table;
  23. return $this;
  24. }
  25. //文件名方法$field
  26. public function field($field)
  27. {
  28. $this->field=$field;
  29. return $this;
  30. }
  31. //Limit方法$Limit
  32. public function Limit($Limit)
  33. {
  34. $this->Limit=$Limit;
  35. return $this;
  36. }
  37. //$where方法
  38. public function where($where)
  39. {
  40. $this->where=$where;
  41. return $this;
  42. }
  43. //$select方法
  44. public function select($select)
  45. {
  46. $this->select=$select;
  47. return $this;
  48. }
  49. public function getSql()
  50. {
  51. return printf('SELECT %s FROM $s LIMIT %d',$this->table,$this->field,$this->limit);
  52. }
  53. //执行查询
  54. public function select()
  55. {
  56. return $this->db->query($this->getSql())->fetchAll(PDO::FETCH_ASSOC);
  57. }
  58. }
  59. //工作类
  60. class Db
  61. {
  62. static function __callStatic($method,$args){
  63. $dsn='mysql:host=localhost;dbname=news';
  64. $username='root';
  65. $password='123456tyi';
  66. $query=new Query( $dsn, $username, $password);
  67. //直接委托给query中的具体方法来完成
  68. return call_user_func([$query,$method],...args);
  69. }
  70. }
  71. $res=Db::table('userid')->field('uid,uname')->Limit(1)->select();
  72. echo '<pre>';
  73. print_r($res);
声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议