<?php
//创建单例的数据库类(工具类)
class Db{
//私有的静态的对象
private static $obj = NULL;
private $db_host;
private $db_user;
private $db_psw;
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_psw = $GLOBALS['config']['db_psw'];
$this->db_name = $GLOBALS['config']['db_name'];
$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;
}
//创建私有的连接数据库的方法
private function connectDb(){
if (!@mysql_connect($this->db_host,$this->db_user,$this->db_psw)) {
die(mysql_error());
}
}
//私有的选择数据库的方法
private function selectDb(){
if (!mysql_select_db($this->db_name)) {
die("选择数据库{$this->db_name}出错!");
}
}
//私有的设置字符集
private function setCharset(){
$this->exec("set names {$this->charset}");
}
//公共的执行sql语句的方法:insert,update,delete,set,create,drop等,除select语句外;
public function exec($sql){
$sql = strtolower($sql);
if (substr($sql,0,6)=='select') {
die("该方法不能执行select语句!");
}
return mysql_query($sql);
}
//私有的执行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){
$result = $this->query($sql);
$types = array(
1 => MYSQL_NUM,
2 => MYSQL_BOTH,
3 => MYSQL_ASSOC);
return mysql_fetch_array($result,$types[$type]);
}
//公共获取多行记录的方法
public function fetchAll($sql,$type=3){
$result = $this->query($sql);
$types = array(
1 => MYSQL_NUM,
2 => MYSQL_BOTH,
3 => MYSQL_ASSOC);
//循环所有记录,并存入新的数组中
while($row=mysql_fetch_array($result,$types[$type])){
$arrs[]=$row;
}
return $arrs;
}
//公共的获取记录数的方法
public function rowCount($sql){
$result = $this->query($sql);
return mysql_num_rows($result);
}
}
php创建单例的数据库类(工具类)
最新推荐文章于 2023-04-24 22:29:17 发布