批改狀態(tài):合格
老師批語:limit 后面最多二個值, 沒必要用數(shù)組
php鏈式數(shù)據(jù)庫查詢過程
使用了魔術變量 __callStatic特性 當對找不到對應方法時便會執(zhí)行方法,在__callStatic()方法內(nèi)在使用call_user_func_array()回調(diào) 調(diào)用找對應的方法來執(zhí)行。
小案例插曲 :平時寫PDO后會使用var_dump()快速測試是否鏈接成功,若返回 object(PDO)#1 (0) 會認為已經(jīng)鏈接成功!但并非如此 就算返回這個也不代表成功。。。當時就是默寫少了一個關鍵詞 但測試鏈接成功 所以分段 分塊調(diào)試很重要得冷靜思考為啥查詢語句正確不返回數(shù)據(jù)應該就是 鏈接問題。
self::$pdo=new \PDO('mysql:127.0.0.1;dbname=php','root','root'); //錯誤語句 少關鍵詞
下來看下數(shù)據(jù)庫鏈式查詢小案例圖
Query.php
<?php namespace _chaxun; class Query2 { //鏈接對象 public $pdo=null; //數(shù)據(jù)表 public $table; //返回字段 public $field='*'; //查詢條件 public $where; //數(shù)據(jù)排序 public $order; //顯示數(shù)量 public $limit; //構造方法,鏈接數(shù)據(jù)庫 public function __construct($pdo) { $this->pdo=$pdo; } //設置表名 public function table($tableName) { $this->table=$tableName; return $this;//關鍵性動作 返回一個當前類的實例(返回自己) } //返回字段 public function field($fields='*') { $this->field=empty($fields) ? '*':$fields; return $this; } //數(shù)據(jù)排序 public function order($order='') { $this->order=empty($prder) ? ' ORDER BY '.$order:''; return $this; } //查詢條件 public function where($where='') { $this->where=empty($where) ? $where : ' WHERE '.$where; return $this; } //顯示數(shù)量 public function limit($limit) { //支持偏移量與查詢條數(shù)[5,6] 也可以單獨限制條數(shù) is_array($limit)? $limit="{$limit[0]},{$limit[1]}" :$limit; $this->limit = empty($limit) ? $limit : ' LIMIT ' . $limit; return $this; } //拼裝SQL語句 public function select() { //拼接 $sql='SELECT ' .$this->field //返回字段 .' FROM ' .$this->table //數(shù)據(jù)表 .$this->where //查詢條件 .$this->order //排序 .$this->limit; //查詢字段 //預處理查詢 $stmt = $this->pdo->prepare($sql); $stmt->execute(); // die($stmt->debugDumpParams()); //錯誤調(diào)試 查看sql語句 return $stmt->fetchAll(\PDO::FETCH_ASSOC); } }
點擊 "運行實例" 按鈕查看在線實例
index.php
<?php namespace _0801; require 'Query.php'; use _chaxun\Query2; class Db { //數(shù)據(jù)庫的鏈接對象 protected static $pdo=null; //鏈接方法 public static function connection() { self::$pdo=new \PDO('mysql:host=127.0.0.1;dbname=php','root','root'); } public static function __callStatic($name,$arguments) { //鏈接數(shù)據(jù)庫 self::connection(); //實例化一個查詢類, $query=new Query2(self::$pdo); //執(zhí)行查詢類中的方法 return call_user_func_array([$query,$name],$arguments); } } $datas=Db::table('staff')//查詢staff表 ->field('age,name,mobile')//返回 age,name ,mobile字段的數(shù)據(jù) ->order('age desc')//以年齡降序排序 ->limit([3,50])//查詢50條數(shù)據(jù) 從第4條開始 ->where('age>35 AND mobile LIKE "%13%"')//年齡大于35歲 并且手機號包含13數(shù)字 ->select(); //var_dump($datas); foreach ($datas as $data){ print_r($data); echo '<br>'; }
點擊 "運行實例" 按鈕查看在線實例
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號