建立数据库访问类的封装
<?php
class
DBDA
{
public
$host
=
"localhost"
;
//服务器地址
public
$uid
=
"root"
;
//数据库的用户名
public
$pwd
=
""
;
//数据库的密码
public
$dbname
=
""
;//数据库名
//执行SQL语句,返回相应结果的函数
//$sql是要执行的SQL语句
//$type是SQL语句的类型,0代表增删改,1代表查询
//$db代表要操作的数据库
public
function
Query(
$sql
,
$type
=1,
$db
=
"xm_youxiang"
)
{
//造连接对象
$conn
=
new
MySQLi(
$this
->host,
$this
->uid,
$this
->pwd,
$db
);
//判断连接是否成功
!mysqli_connect_error()
or
die
(
"连接失败!"
);
//执行SQL语句
$result
=
$conn
->query(
$sql
);
//判断SQL语句类型
if
(
$type
==1)
{
//如果是查询语句返回结果集的二维数组
return
$result
->fetch_all();
}
else
{
//如果是其他语句,返回true或false
return
$result
;
}
}
单例模式连接数据库封装类
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(){
if(!self::$b){
self::$b = mysql_connect($this->dbquery['host'],$this->dbquery['uid'],$this->dbquery['password']);
if(!self::$b){
die('mysql error'.mysql_error());
}
//mysql_select_db($this->dbquery['dbname'],self::$b);
//mysql_query("set names UTF8",self::$b);
}
return self::$b;
}
}
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(){
if(!self::$b){
self::$b = mysql_connect($this->dbquery['host'],$this->dbquery['uid'],$this->dbquery['password']);
if(!self::$b){
die('mysql error'.mysql_error());
}
//mysql_select_db($this->dbquery['dbname'],self::$b);
//mysql_query("set names UTF8",self::$b);
}
return self::$b;
}
}
使用时直接实例化
eg:$connect = DB::show()->connect();