php创建单例的数据库类(工具类)

本文介绍了如何在PHP中创建一个使用单例模式的数据库工具类,以确保在整个应用程序中只存在一个数据库连接实例,从而优化资源管理和提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?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);
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值