批改状态:未批改
老师批语:
<?php
//方法重载案例:数据库连接
require 'check.php';
class db
{
//1、连接数据库
protected static $pdo = null;
public static function pdo()
{
self::$pdo =new PDO('mysql:host=127.0.0.1;dbname=php','root','root');
}
//2、
public static function __callStatic($name,$arr)
{
self::pdo(); //每次增删改查都先连接数据库
//var_dump(self::$pdo);
$hr = new sql(self::$pdo); //创建查询对象,实例化check.php中 sql 类
echo '<pre>' . print_r($arr,true); // $arr 为只有一个元素的 数组,= ['movies']
return call_user_func_array([$hr,$name],[$arr[0]]);
}
}
//客户端的链式带哦用
// 以Db类做入整数数据库操作的入口, SQL语句的各个部分用对象方法提供
// 链式操作是现代PHP框架的基础,非常有用
$qw = db::table('movies')
->field('')
->where('mov_id > 2')
->limit(3)
->select();
foreach ($qw as $qq)
{
print_r($qq); echo '<br>';
}点击 "运行实例" 按钮查看在线实例
<?php
class sql
{
//连接对象pdo
public $pdo;
// 数据表名
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($filed)
{
$this->field=$filed;
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;
// $table = empty($this->table) ? '查询表单为空' : $this->table;
$where = empty($this->where) ? '' : $this->where; // WHERE两边要各加一个空格
$limit = empty($this->limit) ? '' : $this->limit;
//$sql = 'SELECT' . $fields . 'FROM' . $this->table . $where . $limit;
$sql = 'SELECT '. $fields. ' FROM '.$this->table. ' WHERE ' .$where . ' LIMIT ' . $limit; //每个' '中间必须有2个空格
// $sql = 'SELECT * FROM `movies` WHERE id>1 LIMIT 5 ';
$stmt =$this->pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
//没有传查询参数,这里不能用循环打印
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号