- UID
- 1
- 贡献
- 844
- 金币
- 1540
- 主题
- 520
- 在线时间
- 333 小时
- 注册时间
- 2022-1-15
- 最后登录
- 2024-11-12
|
发表于 2022-12-9 11:58:56
| 315 |
0 |
显示全部楼层
|阅读模式
php封装MySQL的单例连接数据库
代码如下:
- <?php
- //封装MySQL单例
- class MySQLDB {
- private $host; //主机地址
- private $port; //端口号
- private $user; //用户名
- private $pwd; //密码
- private $dbname; //数据接名
- private $charset; //字符集
- private $link; //连接对象
- private static $instance;
- private function __construct($param) {
- $this->initParam($param);
- $this->initConnect();
- }
- private function __clone() {
-
- }
- //获取单例
- public static function getInstance($param=array()) {
- if(!self::$instance instanceof self)
- self::$instance=new self($param);
- return self::$instance;
- }
- //初始化参数
- private function initParam($param) {
- $this->host=$param['host']??'127.0.0.1';
- $this->port=$param['port']??'3306';
- $this->user=$param['user']??'';
- $this->pwd=$param['pwd']??'';
- $this->dbname=$param['dbname']??'';
- $this->charset=$param['charset']??'utf8';
- }
- //连接数据库
- private function initConnect() {
- $this->link=@mysqli_connect($this->host,$this->user,$this->pwd,$this->dbname);
- if(mysqli_connect_error()){
- echo '数据库连接失败<br>';
- echo '错误信息:'.mysqli_connect_error(),'<br>';
- echo '错误码:'.mysqli_connect_errno(),'<br>';
- exit;
- }
- mysqli_set_charset($this->link,$this->charset);
- }
- }
- //测试
- //配置参数
- $param=array(
- 'user' => 'root',
- 'pwd' => 'root',
- 'dbname' => 'data'
- );
- //获取单例
- $db=MySQLDB::getInstance($param);
- var_dump($db);
复制代码
数据库是否链接成功打印下,var_dump($db); |
|