批改状态:合格
老师批语:其实这个案例已经涉及到一些设计模式的知识了, 后面的课程, 我们会介绍一些经典的设计模式思想
因为之前创建了PHP.sql,所以我们只要在数据库中加入一张表即可,这里我加入表名 stud

下面是代码部分:
<?php
//这里我给空间命名为_0804
namespace _0804;
class Query
{
// 连接对象,给一个空值null
public $pdo = null;
// 数据表table,但是在编辑器里好像会报错说数据表里没有这个名称
public $table;
public $field = '*';
public $where;
public $limit;
// 构造方法, 连接数据库
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;
}
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语句拼接
public function select()
{
// 拼装
$sql = 'SELECT '
. $this->field // 字段
. ' FROM '
. $this->table // 数据表
. $this->where //条件
. $this->limit;
// 预处理查询
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
// die($stmt->debugDumpParams());
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
}点击 "运行实例" 按钮查看在线实例
<?php
namespace __0804;
require 'Query.php'; //引入Query.php
use _0804\Query;
class Db
{
// 数据库的连接对象
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)
{
// 连接数据库
self::connection();
// 实例 化一个查询类Query.php
$query = new Query(self::$pdo);
// 执行查询类中的方法
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>';
}点击 "运行实例" 按钮查看在线实例
2.执行后效果:

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