写一个接口, 完成基本的数据表操作:CURD
interface iCurd { public function add($data); // 查询 public function select(); // 更新 public function update($data, $where); // 删除 public function del($where); } class DB implements iCurd { protected $pdo = null; protected $table; public function __construct($dsn, $user, $password, $table='user_info') { $this->pdo = new PDO($dsn, $user, $password); $this->table = $table; } public function select($fields='*', $where='', $limit='0, 10') { $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 add($data) { $fields = ' (name,age,sex,position,mobile,hiredate)'; $values = '(:name,:age,:sex,:position,:mobile,:hiredate)'; $sql = 'INSERT INTO '.$this->table.$fields.' VALUES '.$values; $stmt = $this->pdo->prepare($sql); $stmt->execute($data); return [ 'count'=>$stmt->rowCount(), 'id'=>$this->pdo->lastInsertId() ]; } 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; $stmt = $this->pdo->prepare($sql); $stmt->execute($data); // 返回被更新数量 return $stmt->rowCount(); } public function delete($where) { $sql = 'DELETE FROM '.$this->table.' WHERE '.$where; $stmt = $this->pdo->prepare($sql); $stmt->execute(); return $stmt->rowCount(); } }