登录  /  注册
博主信息
博文 49
粉丝 0
评论 4
访问量 40599
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
自己封装一个数据库常用操作类Query.php
过儿的博客
原创
927人浏览过

query.php

实例

<?php
    class Query{
        public $pdo = null;
        public $table = '';
        public $field = '';
        public $where = '';
        public $limit = 0;

        public function __construct($pdo){
            $this->pdo =$pdo;
        }

        public function table($tablename){
            $this -> table =$tablename;
            return $this;
        }
        public function field($fields){
            $this -> field =$fields;
            return $this;
        }
        public function where($where){
            $this -> where =$where;
            return $this;
        }
        public function limit($limit){
            $this -> limit =$limit;
            return $this;
        }
        public function select(){
            $fields = empty($this->field) ? '*' :$this -> field;
            $where = empty($this->where) ? '' : ' WHERE ' .$this->where;
            $limit = empty($this->limit) ? '' : ' LIMIT ' .$this->limit;

            $sql = 'SELECT '.$fields.' FROM '.$this->table. $where . $limit;
            
            $stmt = $this->pdo->prepare($sql);
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
    }
?>

运行实例 »

点击 "运行实例" 按钮查看在线实例

demo06.php

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
   
    <?php 
    require 'Query.php';
      class Db{
          protected static $pdo = null;

          protected static function connection(){
             self::$pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); 
          }
          public static function __callStatic($name,$arguments){
               self::connection();

               $query = new Query(self::$pdo);
               return call_user_func_array([$query,$name],[$arguments[0]]);
          }
      }

      $staffs = Db::table('staff')
      ->field('id,name,position,mobile')
      ->where('id > 5')
      ->limit(5)
      ->select();

            foreach($staffs as $staff){
                print_r($staff);
                echo '<br/>';
            }
    ?>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

1.png

批改状态:合格

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

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

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