单例模式写php连接mysql数据库类

8 篇文章 0 订阅
<?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);
	}
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值