接口属于抽象类的上一级,属于最顶级的接口。
接口的声明函数 interface
继承接口的函数和继承基本类不同,函数为implements 用法与继承基础类相同
接口类的声明必须是public 继承的子类必须完全实现接口的声明操作
总结:总体用法与类的声明与继承用法相同,只是函数名称不同。
用接口类加基础类实现数据库的连接与操作
<?php
//接口实战
//定义一个数据库访问接口:GURD 增删改查
interface iCurd
{
// 增加数据
public function create($data);
// 读取数据
public function read();
// 更改数据
public function update($data,$where);
// 删除数据
public function delete($where);
}
//创建db类,实现iCurd接口
class Db implements iCurd
{
// 连接对象
public $pdo = null;
// 数据库表
protected $table;
// 构造方法,在这个方法完成数据库的连接,还要设置默认的数据表
public function __construct($dns,$user,$password,$table='movies')
{
$this->pdo = new PDO($dns,$user,$password);
$this->table = $table;
}
// 增加数据 重写接口方法
public function create($data)
{
// TODO: Implement create() method.
$fields = ' (name,image,detail,cate_id)';
$values = '(:name,:image,:detail,:cate_id)';
$sql = 'INSERT INTO '.$this->table.$fields.' VALUES '.$values;
$stmt = $this->pdo->prepare($sql);
// print_r($data);die;
$stmt->execute($data);//传递进来的值 这个值是数组
// 返回新增加数量,新增记录ID组成的数组
return ['count'=>$stmt->rowCount(),'id'=>$this->pdo->lastInsertId()];
}
// 读取操作 重写接口方法
public function read($fields='*',$where='',$limit='0,5')
{
// TODO: Implement read() method.
// 设置查询条件
$where = empty($where) ? '' : ' WHERE ' . $where;
// 设置显示数量
$limit = ' LIMIT ' . $limit;
// 预处理
$sql = 'SELECT '. $fields .' FROM '.$this->table.$where.$limit;
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// 更新数据 重写接口方法
public function update($data, $where)
{
// TODO: Implement update() method.
$where = empty($where) ? '' : ' WHERE '.$where;
$keyArr = array_keys($data);
$set = '';
foreach ($keyArr as $value)//获取数组的键0=>name,1=>detail
{
$set .= $value . '= :' .$value. ',';
}
$set =rtrim($set,', ');//利用rtrim删除最后一个逗号和空格
$sql = 'UPDATE '.$this->table.' SET '.$set.$where;
$stmt = $this->pdo->prepare($sql);
$stmt->execute($data);
// 返回被更新的记录数量
return $stmt->rowCount();
}
// 删除数据 重写接口方法
public function delete($where)
{
// TODO: Implement delete() method.
$where = empty($where) ? '' : ' WHERE '.$where;
$sql = 'DELETE FROM '.$this->table.$where;
$stmt = $this->pdo->prepare($sql);
$stmt->execute();
return $stmt->rowCount();
}
}
$db =new Db('mysql:host=localhost;dbname=php','root','root');
//查询
//echo '<pre>'.print_r($db->read('name,image','',1),true);
//echo '<hr>';
//增加
//$data = [
// 'name'=>'梁伟',
// 'image'=>'yttlj.jpg',
// 'detail'=>'是个大帅哥',
// 'cate_id'=>3
//];
//$res = $db->create($data);
//echo '成功新增'.$res['count'].'条记录,最新记录的主键ID是'.$res['id'];
//删除
//echo '成功删除了'.$db->delete('mov_id=10').'条数据';
//更新
$where ='mov_id=11';
$data =[
'name'=>'侍桂琴',
'detail'=>'是个大美女'
];
echo '成功更新了'.$db->update($data,$where).'条记录';点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号