<?php
// 单例模式创建最终的数据库类使用集
final class Db{
//私有的静态的用于对象的属性
private static $obj = NULL;
// 数据库基本属性
private $db_host; //主机名
private $db_user; //用户名
private $db_pass; //密码;
private $db_name; //数据库名
private $charset; //字符编码
// 私有的构造方法,阻止类外new对象,,,,
// 对象的初始化(给属性赋值)
private function __construct(){
$this->db_host = $GLOBALS['config']['db_host'];
$this->db_user = $GLOBALS['config']['db_user'];
$this->db_pass = $GLOBALS['config']['db_pass'];
$this->db_name = $GLOBALS['config']['db_name'];
$this->charset = $GLOBALS['config']['charset'];
$this->connectDb();
$this->selectDb();
$this->setCharset();
}
//私有的克隆方法,组织类外克隆对象
private function __clone(){}
// 共有的静态的,创建对象的方法
public static function getInstance(){
// 判断该对象是否是该类的对象并创建
if (!self::$obj instanceof self) {
self::$obj = new self();
}
// 否则返回
return self::$obj;
}
//私有的连接数据库u服务器的方法
private function connectDb(){
if (!@mysql_connect($this->db_host,$this->db_user,$this->db_pass))
die('PHP连接MYSQL服务器失败');
}
// 私有的连接数据库的方法
private function selectDb(){
if (!mysql_select_db($this->db_name)) die('选择数据库失败');
}
//设置字符集的方法
private function setCharset(){
$this->exec("set names $this->charset");
}
// 数据库对数据增删改的方法,
public function exec($sql){
$sql = strtolower($sql);
if (!substr($sql,0,6)=='select') {
die('该方法不能执行select 语句');
}
return mysql_query($sql);
}
//执行select语句的方法
private function query($sql){
$sql = strtolower($sql);
if (!substr($sql,0,6)=='select') {
die('此方法只能执行select语句');
}
return mysql_query($sql);
}
// 返回单行结果集的方法
public function fetchOne($sql,$type=3){
// 执行sql语句
$result = $this->query($sql);
$types = array(
1 => MYSQL_NUM,
2 => MYSQL_BOTH,
3 => MYSQL_ASSOC
);
return mysql_fetch_array($result,$types[3]);
}
// 返回多行数据
public function fetchArray($sql,$type=3){
//执行sql语句
$res = $this->query($sql);
$types = array(
1 => MYSQL_NUM,
2 => MYSQL_BOTH,
3 => MYSQL_ASSOC
);
$arr = array();
while($row = mysql_fetch_array($res,$types[3])){
$arr[] = $row;
}
return $arr;
}
//获取记录行的方法
public function getCount($sql){
$res = $this->query();
return mysql_num_rows($res);
}
}