PHP数据库单例模式

数据库操作基类  

// 配置文件
<?php
$db = array(
		'host'=>'localhost',
		'user'=>'root',
		'password'=>'',
		'database'=>'test',
)
	
?>
//php 类
<?php
class db {
	public $conn;
	public static $sql;
	public static $instance=null;
	private function __construct(){
		require_once('db.config.php');
		$this->conn = mysql_connect($db['host'],$db['user'],$db['password']);
		if(!mysql_select_db($db['database'],$this->conn)){
			echo "失败";
		};
		mysql_query('set names utf8',$this->conn);		
	}
	public static function getInstance(){
		if(is_null(self::$instance)){
			self::$instance = new db;
		}
		return self::$instance;
	}
	/**
	 * 查询数据库
	 */
	public function select($table,$condition=array(),$field = array()){
		$where='';
		if(!empty($condition)){
			
			foreach($condition as $k=>$v){
				$where.=$k."='".$v."' and ";
			}
			$where='where '.$where .'1=1';
		}
		$fieldstr = '';
		if(!empty($field)){
			
			foreach($field as $k=>$v){
				$fieldstr.= $v.',';
			}
			 $fieldstr = rtrim($fieldstr,',');
		}else{
			$fieldstr = '*';
		}
		self::$sql = "select {$fieldstr} from {$table} {$where}";
		$result=mysql_query(self::$sql,$this->conn);
		$resuleRow = array();
		$i = 0;
		while($row=mysql_fetch_assoc($result)){
			foreach($row as $k=>$v){
				$resuleRow[$i][$k] = $v;
			}
			$i++;
		}
		return $resuleRow;
	}
	/**
	 * 添加一条记录
	 */
	 public function insert($table,$data){
	 	$values = '';
	 	$datas = '';
	 	foreach($data as $k=>$v){
	 		$values.=$k.',';
	 		$datas.="'$v'".',';
	 	}
	 	$values = rtrim($values,',');
	 	$datas   = rtrim($datas,',');
	 	self::$sql = "INSERT INTO  {$table} ({$values}) VALUES ({$datas})";
		if(mysql_query(self::$sql)){
			return mysql_insert_id();
		}else{
			return false;
		};
	 }
	 /**
	  * 修改一条记录
	  */
	public function update($table,$data,$condition=array()){
		$where='';
		if(!empty($condition)){
			
			foreach($condition as $k=>$v){
				$where.=$k."='".$v."' and ";
			}
			$where='where '.$where .'1=1';
		}
		$updatastr = '';
		if(!empty($data)){
			foreach($data as $k=>$v){
				$updatastr.= $k."='".$v."',";
			}
			$updatastr = 'set '.rtrim($updatastr,',');
		}
		self::$sql = "update {$table} {$updatastr} {$where}";
		return mysql_query(self::$sql);
	}
	/**
	 * 删除记录
	 */
	 public function delete($table,$condition){
	 	$where='';
		if(!empty($condition)){
			
			foreach($condition as $k=>$v){
				$where.=$k."='".$v."' and ";
			}
			$where='where '.$where .'1=1';
		}
		self::$sql = "delete from {$table} {$where}";
		return mysql_query(self::$sql);
		
	 }
	
	public static function getLastSql(){
		echo self::$sql;
	}
	
	
	
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值