批改狀態(tài):合格
老師批語(yǔ):其實(shí)這個(gè)案例已經(jīng)涉及到一些設(shè)計(jì)模式的知識(shí)了, 后面的課程, 我們會(huì)介紹一些經(jīng)典的設(shè)計(jì)模式思想
因?yàn)橹皠?chuàng)建了PHP.sql,所以我們只要在數(shù)據(jù)庫(kù)中加入一張表即可,這里我加入表名 stud
下面是代碼部分:
<?php //這里我給空間命名為_(kāi)0804 namespace _0804; class Query { // 連接對(duì)象,給一個(gè)空值null public $pdo = null; // 數(shù)據(jù)表table,但是在編輯器里好像會(huì)報(bào)錯(cuò)說(shuō)數(shù)據(jù)表里沒(méi)有這個(gè)名稱 public $table; public $field = '*'; public $where; public $limit; // 構(gòu)造方法, 連接數(shù)據(jù)庫(kù) public function __construct($pdo) { $this->pdo = $pdo; } // 設(shè)置表名 public function table($tableName) { $this->table = $tableName; //返回一個(gè)當(dāng)前類(lèi)實(shí)例 return $this; } public function field($fields = '*') { $this->field = empty($fields) ? '*' : $fields; return $this; } public function where($where = '') { $this->where = empty($where) ? $where : ' WHERE ' . $where; return $this; } public function limit($limit) { $this->limit = empty($limit) ? $limit : ' LIMIT ' . $limit; return $this; } // SQL語(yǔ)句拼接 public function select() { // 拼裝 $sql = 'SELECT ' . $this->field // 字段 . ' FROM ' . $this->table // 數(shù)據(jù)表 . $this->where //條件 . $this->limit; // 預(yù)處理查詢 $stmt = $this->pdo->prepare($sql); $stmt->execute(); // die($stmt->debugDumpParams()); return $stmt->fetchAll(\PDO::FETCH_ASSOC); } }
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
<?php namespace __0804; require 'Query.php'; //引入Query.php use _0804\Query; class Db { // 數(shù)據(jù)庫(kù)的連接對(duì)象 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ù)庫(kù) self::connection(); // 實(shí)例 化一個(gè)查詢類(lèi)Query.php $query = new Query(self::$pdo); // 執(zhí)行查詢類(lèi)中的方法 return call_user_func_array([$query, $name], $arguments); } } //$staffs = Db::table('staff')->select(); $studs = Db::table('stud') ->field('stud_id, name,age,mobile') ->where('stud_id > 0') //展示大于0的ID ->limit(5) ->select(); foreach ($studs as $stud) { print_r($stud); echo '<br>'; }
點(diǎn)擊 "運(yùn)行實(shí)例" 按鈕查看在線實(shí)例
2.執(zhí)行后效果:
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)