建立数据库访问类的封装
<?php
class
DBDA
{
public
$host
=
"localhost"
;
public
$uid
=
"root"
;
public
$pwd
=
""
;
public
$dbname
=
""
;//数据库名
public
function
Query(
$sql
,
$type
=1,
$db
=
"xm_youxiang"
)
{
$conn
=
new
MySQLi(
$this
->host,
$this
->uid,
$this
->pwd,
$db
);
!mysqli_connect_error()
or
die
(
"连接失败!"
);
$result
=
$conn
->query(
$sql
);
if
(
$type
==1)
{
return
$result
->fetch_all();
}
else
{
return
$result
;
}
}
单例模式连接数据库封装类
单例模式有三大原则:
构造函数不能为public
有一个保存实例的静态成员变量
拥有访问这个实例的公共静态方法
基于单例模式的PHP数据库连接类:
class DB{
static private $a; //实例变量
static private $b; //
private $dbquery = array(
'host' => 'localhost',
'uid' => 'root',
'password' => '',
'dbname' =>'数据库名',
);
private function __construct(){
}
static public function show(){
if(!(self::$a aof self)){
self::$a = new self();
}
return self::$a;
}
public function connect(){