Blogger Information
Blog 28
fans 1
comment 0
visits 17537
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
2019.6.18作业
关超的博客
Original
621 people have browsed it

写一个接口, 完成基本的数据表操作: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();
    }
}


Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post