PDO链式操作

<?php

// 数据库以及系统公用参数
$C = [
    // 数据库类型
    'DB_TYPE' => 'mysql',
    // 服务器地址
    'DB_HOST' => '127.0.0.1',
    // 数据库名
    'DB_NAME' => 'test',
    // 用户名
    'DB_USER' => 'root',
    // 密码
    'DB_PWD'  => 'root',
    // 端口
    'DB_PORT' => '3306',
    // 数据库表前缀
    'DB_PREFIX' => '',
    // 数据库编码
    'DB_CHARSET' => 'utf8',
];

class Database
{
    // 数据库类型
    protected $dbType;
    // 数据库主机名
    protected $dbHost;
    // 数据库名称
    protected $dbName;
    // 数据库编码
    protected $dbCharset;
    // 数据库连接用户名
    protected $dbUser;
    // 对应的密码
    protected $dbPwd;
    // 数据表前缀
    protected $tablePrefix;
    // 数据表名(不包含表前缀)
    protected $tableName;
    // 数据表名(已包含表前缀)
    protected $trueTableName;
    // 记录需要执行的SQL语句
    protected $dbSql;
    // 连贯操作参数
    protected $linkOperation = array(
        'field' => '*',
        'where' => '',
        'order' => '',
        'page' => '',
        'limit' => '',
    );

    // 数据库PDO连接实例
    private $pdo;

    // 存储服务实例
    protected static $instance;

    /**
     * 获取单例实例
     *
     * @return static
     */
    public static function instance()
    {
        if (static::$instance instanceof static) {
            return static::$instance;
        }
        static::$instance = new static();

        return static::$instance;
    }

    // 构造方法
    public function __construct()
    {
        // 获得配置信息
        global $C;
        $this->dbType = $C['DB_TYPE'];
        $this->dbHost = $C['DB_HOST'];
        $this->dbName = $C['DB_NAME'];
        $this->dbCharset = $C['DB_CHARSET'];
        $this->dbUser = $C['DB_USER'];
        $this->dbPwd = $C['DB_PWD'];
        $this->tablePrefix = $C['DB_PREFIX'];
        // 初始化PDO类
        $this->dbPdo();
    }

    // 数据库连接
    private function dbPdo()
    {
        try {
            $dbn = $this->dbType . ':host=' . $this->dbHost . ';dbname=' . $this->dbName . ';charset=' . $this->dbCharset;
            $dbh = new PDO($dbn, $this->dbUser, $this->dbPwd);
            $this->pdo = $dbh;
        } catch (\Throwable $th) {
            // throw $th;
            echo '数据库连接失败:' . $th->getMessage();
        }
    }

    // 拼接Sql
    private function dbSqli()
    {
        $where = !empty($this->linkOperation['where']) ? ' WHERE ' . $this->linkOperation['where'] : '';
        $order = !empty($this->linkOperation['order']) ? ' ORDER BY ' . $this->linkOperation['order'] : '';
        $page = !empty($this->linkOperation['page']) ? $this->linkOperation['page'] - 1 : '';
        if ($page) {
            $limit = !empty($this->linkOperation['limit']) ? ' LIMIT ' . $page * $this->linkOperation['limit'] . ',' . $this->linkOperation['limit'] : '';
            $sql = 'SELECT ' . $this->linkOperation['field'] . ' FROM ' . $this->trueTableName . $where . $order . $limit;
        } else {
            $limit = !empty($this->linkOperation['limit']) ? ' LIMIT ' . $this->linkOperation['limit'] : '';
            $sql = 'SELECT ' . $this->linkOperation['field'] . ' FROM ' . $this->trueTableName . $where . $order . $limit;
        }
        $this->dbSql = $sql;
    }

    // 操作指定表名
    public function table($tableName)
    {
        $this->trueTableName = $this->tablePrefix . $tableName;
        $this->tableName = $tableName;
        return $this;
    }

    // 指定查询结果集中的返回字段
    public function field($name)
    {
        switch (gettype($name)) {
            case 'string':
                $this->linkOperation['field'] = $name;
                break;
            case 'array':
                $this->linkOperation['field'] = implode(', ', $name);
                break;
            default:
                # code...
                break;
        }
        return $this;
    }

    // 查询条件
    public function where($name)
    {
        switch (gettype($name)) {
            case 'string':
                $this->linkOperation['where'] = $name;
                break;
            case 'array':
                $string = '';
                foreach ($name as $key => &$value) {
                    $string .= $key . ' = ' . $value . ' AND ';
                }
                $string = rtrim($string, ' AND ');
                $this->linkOperation['where'] = $string;
                break;

            default:
                # code...
                break;
        }
        return $this;
    }

    // 指定字段排序
    public function order($name)
    {
        $this->linkOperation['order'] = $name;
        return $this;
    }

    // 分页查询
    public function page($name)
    {
        $this->linkOperation['page'] = $name;
        return $this;
    }

    // 查询分页
    public function limit($name)
    {
        $this->linkOperation['limit'] = $name;
        return $this;
    }

    // 执行SELECT查询获取单条记录,返回一维数组
    public function find()
    {
        $this->dbSqli();
        $pdo = $this->pdo;
        $res = $pdo->query($this->dbSql);
        // 键值索引方式
        $res->setFetchMode(PDO::FETCH_ASSOC);
        if (!empty($_GET['debug'])) {
            echo '<pre>';
            echo $res->debugDumpParams();
        }
        return $res->fetch();
    }

    // 执行SELECT获取所有记录,返回二维数组
    public function select()
    {
        $this->dbSqli();
        $pdo = $this->pdo;
        $res = $pdo->query($this->dbSql);
        // 键值索引方式
        $res->setFetchMode(PDO::FETCH_ASSOC);
        if (!empty($_GET['debug'])) {
            echo '<pre>';
            echo $res->debugDumpParams();
        }
        return $res->fetchAll();
        // $array = array();
        // while ($row = $res->fetch()) {
        //     $array[] = $row;
        // }
        // return $array;
    }
}

Database::instance()->table('xquser')->where(['pid' => 100000])->order('id desc')->page(3)->limit(5)->select();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值