PDO方式封装数据库类

PDO方式封装数据库类(仅供参考)

    public function connect()
    {
        $dsn = $this->config['type'].":host=".$this->config['host'].";dbname=".$this->config['databasename'];
        $this->pdo = new PDO($dsn,$this->config['user'],$this->config['pwd']);
        return $this->pdo;
    }
    /**
     * @param $param
     * @return $this
     * 设置表名
     */
    public function table($param)
    {
        $this->table = $param;
        return $this;
    }

    public function where($where)
    {
        $this->where = $where;
        return $this;
    }

    /**
     * 查询所有的mysqli方式
     */
    public function all()
    {
        $sql = "select * from ".$this->table." where ".$this->where;
//        $res = $this->pdo->query($sql)->fetchAll();
        /**
         * PDO设置
         */
        if($this->getresult == "num"){
            $res = $this->pdo->query($sql)->fetchAll(PDO::FETCH_NUM);
        }elseif($this->getresult == "assoc"){
            $res = $this->pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
        }else{
            $res = $this->pdo->query($sql)->fetchAll();
        }
        return $res;
    }
    /**
     * @return array|null
     * 查询单条数据 mysqli方式
     */
    public function get()
    {
        $sql = "select * from ".$this->table." where ".$this->where;
        /**
         * PDO设置
         */
        if($this->getresult == "num"){
            $res = $this->pdo->query($sql)->fetch(PDO::FETCH_NUM);
        }elseif($this->getresult == "assoc"){
            $res = $this->pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
        }else{
            $res = $this->pdo->query($sql)->fetch();
        }
        return $res;
    }

    /**
     * @content PDO
     */
    public function delete()
    {
        $sql = 'delete from '.$this->table .$this->where;
        $res = $this->pdo->prepare($sql);
        $id = 9;
        $res->bindValue(1,$id);
        $res->execute();
        $affect_row = $res->rowCount();
        return $affect_row;
    }

    /**
     * 关联数据
     */
    public function getnum()
    {
        $this->getresult = "num";
        return $this;
    }

    /**
     * 索引数组
     */
    public function getassoc()
    {
        $this->getresult = "assoc";
        return $this;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值