Correction status:qualified
Teacher's comments:接口中的参数, 要看协议
interface iCurd { //查询数据 public function select(); //删除数据 public function delete($where); //更新数据 public function update($data, $where); //添加数据 public function insert($data); } class Db implements iCurd { //定义数据库的连接对象 protected $pdo; //定义数据库连接的数据表 protected $table; public function __construct($dsn, $user, $password, $table = 'user') { $this->pdo = new \PDO($dsn, $user, $password); $this->table = $table; } //查询数据 public function select($fields = '*', $where = '') { $where = empty($where) ? '' : ' WHERE ' . $where; //拼装sql语句 $sql = 'SELECT ' . $fields . ' FROM ' . $this->table . $where; $stmt = $this->pdo->prepare($sql); $stmt->execute(); return $stmt->fetchAll(\PDO::FETCH_ASSOC); } //删除数据 public function delete($where) { $where = empty($where) ? '' : ' WHERE ' . $where; $sql = 'DELETE ' . ' FROM ' . $this->table . $where; $stmt = $this->pdo->prepare($sql); $stmt->execute(); echo '成功删除了' . $stmt->rowCount() . '条记录!'; } //更新数据 public function update($data, $where) { $keyArr = array_keys($data); $set = ''; foreach ($keyArr as $value) { $set .= $value . ' = :' . $value . ', '; } $set = rtrim($set, ', '); $sql = 'UPDATE ' . $this->table . ' SET ' . $set . ' WHERE ' . $where; //die($sql); $stmt = $this->pdo->prepare($sql); $stmt->execute($data); echo '成功更新 ' . $stmt->rowCount() . '记录'; } //添加数据 public function insert($data) { //列字段 $fields = ' (name,sex,age) '; $values = ' (:name,:sex,:age) '; $sql = 'INSERT INTO ' . $this->table . $fields . ' VALUES ' . $values; //die($sql); $stmt = $this->pdo->prepare($sql); $stmt->execute($data); echo '成功添加' . $stmt->rowCount() . '条记录!' . '<br>'; echo '新记录的ID是:' . $this->pdo->lastinsertid(); } } //调用 $dsn = 'mysql:host=127.0.0.1;dbname=cksjk'; $user = 'wcz'; $password = '210584'; $table = 'user'; $db = new Db($dsn, $user, $password, $table); //查询 //foreach ($db->select() as $item) { // print_r($item); echo '<br>'; //} //echo '<hr>'; //删除 //$db->delete('id=2'); //新增 //$data = ['name' => "wcgz", 'sex' => 1, 'age' => 25]; //$db->insert($data); $data = ['age' => 38 ]; $where = "name='wcz'"; $db->update($data, $where);
点击 "运行实例" 按钮查看在线实例
总结:
1,接口就是类的模板,里面的方法是子类必须全部实现的,如果仅部分实现,用抽象类实现;
2,接口中只能有方法或类常量,不能声明变量成员;
3,接口中的方法都是public类型的,因为大家都要用;
4,接口中的方法都是空的,参数可有可无;