批改状态:合格
老师批语:问一下自己, 如果让你自己写, 能否写出来, 会卡在哪里, 这样才会进步
在线运行地址:http://www.pursuer.top/sql/index.php
query.php
主要是创建sql执行语句,链式调用关键在return $this;
<?php
namespace sql;
class Query
{
// pdo对象
public $pdo = null;
// 数据表
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 = '*'){
// empty判断是否有值,有值为值,无值默认
$this->field = empty($fields) ? '*' : $fields;
return $this;
}
// 设置查询条件
public function where($where = ''){
// empty()判断值,第一个$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();
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
}点击 "运行实例" 按钮查看在线实例
index.php
连接数据库,执行sql语句
<?php
namespace sql;
require 'Query.php';
use sql\Query;
class Db
{
// 连接数据库对象
protected static $pdo = null;
// 连接方法
public static function connection(){
self::$pdo = new \PDO(
'mysql:host=127.0.0.1;dbname=books','root','root');
}
public static function __callStatic($name,$arguments){
// 连接数据库
self::connection();
$query = new Query(self::$pdo);
return call_user_func_array([$query,$name], $arguments);
}
}
$books = Db::table('books')
->field('book_id,book_name,book_author,book_desc')
->where('book_id > 5')
->limit(5)
->select();
foreach ($books as $book) {
print_r($book); echo '<hr>';
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号