批改状态:合格
老师批语:
<?php
/**
* 定义类数据库查询
*/
class Query
{
//保存SQL语句中的各个组成部份
private $sql = [];
//数据库连接对象
private $pdo = null;
//构造方法:连接数据库
public function __construct()
{
//给一个方法来连接数据库
$this->pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
}
//tbale()来获取SQL语句的表句
public function table($table)
{
$this->sql['table'] = $table;
return $this;//返回当前类实例对象,便于链式调用该对象的其它方法
}
//fields()来获取查询的字段列表
public function fields($fields)
{
$this->sql['fields'] = $fields;
return $this;
}
//查询的条件
public function where($where)
{
$this->sql['where'] = $where;
return $this;
}
//检查的终极方法//查询具体语句
public function select()
{
$sql = "SELECT {$this->sql['fields']} FROM {$this->sql['table']} WHERE {$this->sql['where']}";
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}点击 "运行实例" 按钮查看在线实例
调用执行
<?php
/**
* 使用方法重载与call_user_func_array()模拟TP框架的链式查询
* 用方法的重载实现方法跨类调用
*/
require 'Query.php';
//Db::tbale()->fields()->where()->select();
//数据库操作的入口类
class Db
{
public static function __callStatic($name, $arguments)
{
//call_user_func_array([类名,方法],[])的使用方法与参数
return call_user_func_array([(new Query()),$name],$arguments);
}
}
$result = Db::table('user')->fields('id,name,email,age')->where('id>0')->select();
echo '<pre>';
echo var_export($result);
echo '<hr>';
foreach ($result as $sum)
{
echo $sum['id'],$sum['name'],$sum['email'],$sum['age'].'<br>';
}
echo count($result);点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号