博主信息
博文 15
粉丝 0
评论 0
访问量 11161
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
数据库查询构造器
ッ小眼睛っ
原创
1371人浏览过

作业问题:

代码:

  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'));
批改老师:PHPzPHPz

批改状态:合格

老师批语:
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学