Correction status:qualified
Teacher's comments:通过这个案例你学到了什么呢? 复制代码谁都会, 最好谈点学后感...
<?php namespace _0802; interface DbCrud { public function create($data); public function read(); public function update($data,$where); public function delete($where); } class Db implements DbCrud { protected $pdo=null; protected $user; public function __construct($pdo,$username,$password,$user) { $this->pdo = new \PDO($pdo,$username,$password); $this->user = $user; } public function create($data) { $fields = '(name,age)'; $values = '(:name,:age)'; $sql = 'INSERT INTO '.$this->user . $fields . ' VALUES ' . $values; $smpt=$this->pdo->prepare($sql); $smpt->execute($data); return [ 'count'=>$smpt->rowCount(), 'id'=>$this->pdo->lastInsertId() ]; } public function read($fields = '*' , $where='', $limit = '0, 5') { $where = empty($where) ? '' : ' WHERE ' . $where; $limit = ' LIMIT ' . $limit; $sql = 'SELECT '. $fields . ' FROM ' . $this->user. $where . $limit; $stmt = $this->pdo->prepare($sql); $stmt->execute(); return $stmt->fetchAll(\PDO::FETCH_ASSOC); } public function update($data,$where) { $keyArr = array_keys($data); $set = ''; foreach ($keyArr as $value) { $set .= $value . '= :' . $value. ','; } $set =rtrim($set, ', '); $sql = 'UPDATE '. $this->user.' SET '.$set.' WHERE '.$where; $stmt = $this->pdo->prepare($sql); $stmt->execute($data); return $stmt->rowCount(); } public function delete($where) { $sql = 'DELETE FROM '. $this->user. ' WHERE '.$where; $stmt = $this->pdo->prepare($sql); $stmt->execute(); return $stmt->rowCount(); } } $dsn = 'mysql:host=127.0.0.1;dbname=php'; $username='root'; $password='root'; $user='user'; $Db= new Db($dsn, $username,$password,$user); //$data = [ // 'name'=> '杨发国', // 'age'=> 30, // ]; //$res=$Db->create($data); //echo '成功新增了'.$res['count'].'条记录'.'用户ID为'.$res['id']; echo '<hr>'; foreach ($Db->read('id,name,age', 'age >=30') as $item) { print_r($item); echo '<br>'; } echo '<hr>'; $data = [ 'name' => '作业增删改查', 'age' => 50 ]; $where = 'id = 1'; echo '成功的更新了: ' . $Db->update($data, $where) . ' 条记录'; echo '<hr>'; $where = 'id = 30'; echo '成功的删除了: ' . $Db->delete($where) . ' 条记录';
点击 "运行实例" 按钮查看在线实例