数据库的大部分操作都是在sql类中实现的。
本节课我们主要学习什么是链式操作
链式操作主要体现在数据查询上,这里数据查询有两个方法:fetchAll() 和 fetch()
我们先看代码
<?php
namespace fastphp\db;
use fastphp\db\Db;
use \PDOStatement;
class Sql
{
// 数据库表名
protected $table;
private $where;
private $order;
// Pdo bindParam()绑定的参数集合
private $param = array();
//返回的字段
private $fields = '*';
function __construct($table)
{
$this->table = $table;
}
//查询后返回的字段
public function fields($fields)
{
if (!empty($fields)) {
$this->fields = $fields;
}
return $this;
}
/**
* 查询条件
*/
public function where($where = '')
{
if ($where) {
$this->where = ' WHERE ' . $where;
}
return $this;
}
/**
* 排序
*/
public function order($order = '')
{
if ($order) {
$this->order = ' ORDER BY ' . $order;
}
return $this;
}
// 查询所有
public function fetchAll()
{
$sql = sprintf("select %s from `%s` %s %s", $this->fields, $this->table, $this->where,$this->order);
$sth = Db::pdo()->prepare($sql);
$sth->execute();
return $sth->fetchAll();
}
// 查询一条
public function fetch()
{
$sql = sprintf("select %s from `%s` %s %s", $this->fields, $this->table, $this->where,$this->order);
$sth = Db::pdo()->prepare($sql);
$sth->execute();
return $sth->fetch();
}
}
上面的代码有一个难点:
return $this;
表示方法结束后,返回的是当前对象,它可以实现链式操作。
在该类的下面,我们写一段测试代码:
//测试代码
require_once __DIR__ . '/db.php';
$table = new Sql('student');
$data = $table->fields('no,name')->where("no=101 or sex='男'")->order('no')->fetchAll();
print_r($data);
$data = $table->order('name')->where('no=101')->fetch();
print_r($data);
因为fields() 方法返回的是当前对象,所以它可以继续调用where方法
where() 方法返回的也是当前对象,所以它可以继续执行order() 方法,
仔细观察,上面的链式操作没有先后之分。
链式操作在thinkphp框架使用的非常广泛。