<?php
/*
Mysql数据库连接类
*/
class Easy_Db_Mysql implements Easy_Db_Interface {
	protected static $db;
	public $Cache= false;
	public $querys = 0;
	public function __construct(){
		$array = func_get_arg(0);
		$this->dbhost = (string)$array['dbhost'];
		$this->dbname = (string)$array['dbname'];
		$this->dbuser = (string)$array['dbuser'];
		$this->dbpass = (string)$array['dbpass'];
		$this->Cache = (string)$array['dbcache'];
		$this->charset = $array['dbchar'] ? 	$array['dbchar'] : 'gbk';
		if( FALSE!=(self::$db = @mysql_connect($this->dbhost, $this->dbuser, $this->dbpass)) ){
			$this->exec('use '.$this->dbname);
			if( mysql_get_server_info()> '4.1')
			{
				if(!$this->charset && in_array(strtolower($this->charset, array('gbk', 'big5', 'gbk'))) !== false) {
					$this->charset = str_replace('-', '', $this->charset);
				}
				if($this->charset) {
					$this->query("SET character_set_connection='".$this->charset."', 
					character_set_results='".$this->charset."', character_set_client=binary") or die (mysql_error());;
				}
				if(mysql_get_server_info() > '5.0.1') {
					$this->query("SET sql_mode=''") or die (mysql_error());
				}
			}
		}else{
			die( "数据库连接失败!请检查数据库配置文件!服务器返回<br>".mysql_error());
		}
	}
	/*
	$table 表名称
	$data 需要插入的数据数组
	成功返回插入记录的个数否则返回false
	*/
	public function insert($table, $data){
		$str = null;
		foreach($data as $key=>$value){
			$str.= $str ? ",`$key`" : "`$key`";
			$val.= $val ? ','.$this->quote(trim($value)) : $this->quote(trim($value));
		}
		$this->sql = "INSERT INTO $table($str) VALUES($val)";
		unset($table, $data);
		return $this->exec($this->sql);	//Return number of rows that were Insert
	}	//数据插入
	public function lastInsertId(){
		return mysql_insert_id(self::$db);	//返回插入的记录ID
	}
	/*
	$table 表名称
	$where 删除记录的条件
	*/
	public function delete($table, $where = null){
		if (is_array($where)){
			foreach($where as $key=>$value){
				$wheres.= " AND `$key` = ".$this->quote($value);
			}
		}else{
			$wheres = 'AND '. $where;
		}
		$this->sql = "DELETE FROM $table WHERE 1=1 $wheres";
		unset($array, $wheres, $table, $debug, $params);
		return $this->exec($this->sql);
	}		//删除数据
	/*
	数据更新
	$table 表名
	$data 更新数据的数组或者字符。键名为字段名键值为内容。
	$where 更新记录的条件。可以为数组或者字符
	*/
	public function update($table, $data, $where=null){//更新数据
		$str = null;
		$wheres = null;
		if (is_array($data)){
			foreach($data as $key=>$value){
				$str.= (empty($str)===false) ? ",`$key`=".$this->quote($value) : "`$key`=".$this->quote($value);
			}
		}else{
			$str = $data;
		}
		unset($key,$value);
		if (is_array($where)){
			foreach($where as $key=>$value){
				$wheres.= " AND `$key` = ".$this->quote($value);
			}
		}elseif (is_null($where)===false){
			$wheres = 'AND '. $where;
		}else{
			unset($wheres);
		}
		$this->sql = "UPDATE ".$table." SET $str WHERE 1=1 $wheres";
		unset($wheres);
		$this->exec($this->sql);
		return $this->affected_rows();	//返回影响的行数
	}
	/*
	获取记录的全部数据
	$sql  SQL语句
	$type  为查询记录的模式默认为mysql_query 否则为mysql_unbuffered_query
	*/
	public function fetAll($sql, $type=null){//取得数据作为数据
		$sth = $this->query($sql, $type);
		$data =array();
		if (is_resource($sth)){
			while($rs =  mysql_fetch_assoc($sth)){
				$data[] = $rs;
			}
			mysql_free_result($sth);
		}else{
			$this->error('FetAll方法运行时出错!');
		}
		unset($rs);
		return $data;
	}			
	public function fetRow($sql, $type=null)			//取得一行数据作为数组
	{
		$sth = $this->query($sql, $type);
		if (is_resource($sth)){
			$row = mysql_fetch_assoc($sth);
			mysql_free_result($sth);
			return $row;
		}else{
			$this->error('FetRow方法运行时出错!');
		}
	}
	public function fetOne($sql){		//取得第一个字段值
	
	}
	/*
	返回记录总数
	*/
	public function getCount($sql){
		$this->sql =  preg_replace("/^select (.+?) from/is",  "SELECT COUNT(*) as total FROM", $sql);
		//echo $this->sql;
		$row = $this->fetRow($this->sql);
		return $row['total'];
	}
	public function query($sql, $type=null)		//执行一个SQL语句
	{
		$this->querys = $this->querys + 1;
		if (is_object($sql)===true){
			$this->sql = $sql->toString();
		}else{
			$this->sql = $sql;
		}
		if (is_null($type) == false || $this->Cache ){
			$func = 'mysql_unbuffered_query';
		}else{
			$func = 'mysql_query';
		}
		//echo $this->sql;
		//$fp = fopen(ROOT.'sql.log', 'a');
		//fwrite($fp, $sql."\n\t");
		if ( ($sth = $func($this->sql, self::$db)) !==false){
			unset($sql);
			return $sth;
		}else{
			$this->error(mysql_error());
		}
	}
	public function affected_rows(){
		return mysql_affected_rows(self::$db);
	}
	public function beginTransaction()	//开始事务处理
	{
		
	}
	public function commit()				//提交事务
	{
		
	}
	public function rollBack()			//事务失败回滚事务
	{
		
	}
	public function quote($string)		//转义字符
	{
		return '\''.mysql_real_escape_string($string).'\'';
	}
	public function error($error)		//抛出字符信息
	{
		echo '数据库出现了错误:'.$errir.'<br/>';
		echo 'SQL:'.$this->sql.'<br />';
		echo '<解决这个问题请到<a href="">http://wwww.vodcms.com/bbs/</a>查找错误原因<br />';
		//throw new Exception($error.'SQL:'.$this->sql.'<br />请到<a href="">http://wwww.vodcms.com/bbs/</a>查找错误原因');
		exit;
	}
	public function debug($bool=false)				//开启调试
	{
		
	}
	public function select(){
		return new Easy_Db_Select();
	}
	/*
	用于执行更新操作SQL
	*/
	public function Exec($sql, $type=null){
	
		$this->sql = $sql;
		unset($sql);
		return $this->query($this->sql, $type);
	}
	public function showTable($dbname=null){
		if (is_null($dbname)){
			$dbname = $this->dbname;
			//$this->query('SHOW TABLES FROM '.$dbname);
			$data = array();
			foreach($this->fetAll('SHOW TABLES FROM '.$dbname) as $row){
				$data[] = current(array_values($row));
			}
		}
		return $data;
	}
	/**/
	public function version(){
		return mysql_get_server_info(self::$db);
	}
	public function __call($method, $args){
		//$func = '__'.$method;
		//echo $func;
		if(method_exists($this, $func) === false){
			exit('调用了无效的类方法名:'.$method.'<br>错误行数:'.__LINE__.'<br>错误文件'.__FILE__);
		}else{
			return $this->$func($args);
		}
	}
}