Conncetion

作用:主要作用通过构建PDO对象与数据库进行交互

代码解析

属性:

 protected $config = [
//数据类型
'type'=>'',
//服务器地址
'hostname'=>'',
//端口号
'hostport'=>'',
//数据库名
'dbname'=>'',
//用户名
'username'=>'',
//密码
'password'=>''
];
//PDO连接ID 支持多个数据库连接
protected $links = [];

//连接参数
protected $params = [
    PDO::ATTR_CASE => PDO::ATTR_CASE_NATURAL,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_ORACLES_NULLS => PDO::NULL_NATURAL,
    PDO::ATTR_STRINGIFY_FETCHES => false,
    PDO::ATTR_EMULATE_PREPARES =>false
]

protected $fetchType = PDO::FETCH_ASSOC;

初始化:

public function __construct(array $config=[]){
    if(!empty($config)){
        $this->config = array_merge($this->config,$config);
    }
}

连接数据库:

public function connection(array $config=[],$linknum=0,$autoconnection=false){
    if(!isset($this->links[$linknum])){
        if (!$config) {
           $config = $this->config;
        }else{
            $config = array_merge($this->config,$config);
        }
        if(isset($config['params'] && is_array($config['params'])){
            $params = $config['params'] + $this->params;
        }else{
            $params = $this->params;
        }

        if (isset($config['result_type'])){
            $this->fetchType = $config['result_type'];
        }

        if(!isset($config['dsn'])){
            $config['dsn'] = $this->parseDsn($config);
        }

        try{
            $this->links[$linknum] = new PDO($config['dsn'],$config['username'],$config['password'],$params);
        }catch(PDOException $e){
            throw $e;
        }
    }

    return $this->links[$linknum];
}

protected function parseDsn(array $config){
    if(!empty($config['socket'])){
        $dsn = 'mysql:unix_socket='.$config['socket'];
    }elseif (!empty($config['hostport'])) {
        $dsn = 'mysql:host='.$config['hostname'].';port='.$config['hostport'];
    }else{
        $dsn = 'mysql:host='.$config['hostname'];
    }

    $dsn.= ';dbname='.$config['database'];
    if (!empty($config['charset'])) {
         $dsn.= ';charset='.$config['charset'];
    }

    return $dsn;
}
?>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值