28)PHP,数据库连接类
时间:2021-07-01 10:21:17
帮助过:23人阅读
<?
php
2 //类名,也习惯上(推荐)使用跟文件名相似的名字
3 //定义一个类,该类可以连接mysql数据库
4 //并连接后返回资源(或失败就终止)
5 class mysqlDB{
6 public $host;
7 public $port;
8 public $username;
9 public $password;
10 public $charset;
11 public $dbname;
12
13 //连接结果(资源)
14 static $link;
15
16 //构造函数
17 public function __construct($config){
18 //初始化数据
19 $
this->host = isset($config[
‘host‘]) ? $config[
‘host‘] :
‘localhost‘;
20 $
this->port = isset($config[
‘port‘]) ? $config[
‘port‘] :
‘3306‘;
21 $
this->username = isset($config[
‘username‘]) ? $config[
‘username‘] :
‘root‘;
22 $
this->password = isset($config[
‘password‘]) ? $config[
‘password‘] :
‘‘;
23 $
this->charset = isset($config[
‘charset‘]) ? $config[
‘charset‘] :
‘utf8‘;
24 $
this->dbname = isset($config[
‘dbname‘]) ? $config[
‘dbname‘] :
‘‘;
25
26 //连接数据库
27 self::$link = $
this->
connect();
28 //设定连接编码
29 $
this->setCharset($
this->
charset);
30 //选定数据库
31 $
this->selectDb($
this->
dbname);
32 }
33 //这里进行连接
34 public function connect(){
35 $link = mysql_connect(
"$this->host:$this->port",
"$this->username",
"$this->password") or die(
"连接数据库失败!");
36 return $link;
37 }
38 public function setCharset($charset){
39 mysql_set_charset($charset, self::$link);
40 }
41 public function selectDb($dbname){
42 mysql_select_db($dbname, self::$link)
43 }
44 }
45
46 //先设想:
47 $config =
array(
48 ‘host‘=>
‘localhost‘,
49 ‘port‘=>
‘3306‘,
50 ‘username‘=>
‘root‘,
51 ‘password‘=>
‘123‘,
52 ‘charset‘=>
‘utf8‘,
53 ‘dbname‘=>
‘php34‘,
54 );
55 $link =
new mysqlDB( $config );
56 $result = $link->query(
"delete from tab1 where id=1");
大概就是这个样子,我没有试,不过思路就是这个。
28)PHP,数据库连接类
标签:port blog ret span dbn static pre 使用 构造