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>
运行实例 »
点击 "运行实例" 按钮查看在线实例