Blogger Information
Blog 49
fans 0
comment 4
visits 41878
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
自己封装一个数据库常用操作类Query.php
过儿的博客
Original
965 people have browsed it

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

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