<?php
 /*
 * cms 数据库连接文件
 * ============================================================================
 * 版权所有: 快范网络，并保留所有权利。
 * 网站地址: http://www.kuaifan.net；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
*/
if(!defined('IN_KUAIFAN')) exit('Access Denied!');
class mysql {
	var $linkid=null;
	var $ExecuteArr = array(); 

    function __construct($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset = 'UTF8', $connect = 1) {
    	$this -> connect($dbhost, $dbuser, $dbpw, $dbname, $dbcharset, $connect);
    }

    function connect($dbhost, $dbuser, $dbpw, $dbname = '', $dbcharset = 'UTF8', $connect=1){
    	$this->db_name = $dbname;
    	$this->db_charset = $dbcharset;
    	$func = empty($connect) ? 'mysql_pconnect' : 'mysql_connect';
    	if(!$this->linkid = @$func($dbhost, $dbuser, $dbpw, true)){
    		$this->dbshow('Can not connect to Mysql!');
    	} else {
    		if($this->dbversion() > '4.1'){
    			mysql_query( "SET NAMES UTF8");
    			if($this->dbversion() > '5.0.1'){
    				mysql_query("SET sql_mode = ''",$this->linkid);
					mysql_query("SET character_set_connection=".$dbcharset.", character_set_results=".$dbcharset.", character_set_client=binary", $this->linkid);
    			}
    		}
    	}
    	if($dbname){
    		if(mysql_select_db($dbname, $this->linkid)===false){
    			$this->dbshow("Can't select MySQL database($dbname)!");
    		}
    	}
    }

    function select_db($dbname){
    	return mysql_select_db($dbname, $this->linkid);
    }

    function query($sql){
    	$this->ExecuteArr[] = $sql;
    	if(!$query=@mysql_query($sql, $this->linkid)){
    		$this->dbshow("Query <br/>error: $sql");
    	}else{
    		return $query;
    	}
    }

    function getall($sql, $type=MYSQL_ASSOC){
    	$query = $this->query($sql);
    	while($row = mysql_fetch_array($query,$type)){
    		$rows[] = $row;
    	}
    	return $rows;
    }

    function getone($sql, $type=MYSQL_ASSOC){
    	$query = $this->query($sql,$this->linkid);
    	$row = mysql_fetch_array($query, $type);
    	return $row;
    }
	function get_total($sql)
	{
		$row = $this->getall($sql);
		$v=0;
		if (!empty($row) && is_array($row))
		{			
			foreach($row as $n)
			{
			$v=$v+$n['num'];
			}			
		}
		return $v;
 	}
    function getfirst($sql, $type=MYSQL_NUM) {
    	$query = $this->query($sql, $this->linkid);
    	$row = mysql_fetch_array($query, $type);
    	return $row[0];
    }
	function fetch_array($result,$type = MYSQL_ASSOC){
		return mysql_fetch_array($result,$type);
	}

    function affected_rows(){
    	return mysql_affected_rows($this->linkid);
    }

    function num_rows($result = null){
    	if (empty($result)) return mysql_num_rows($this->linkid);
    	return mysql_num_rows($result);
    }

    function num_fields($result){
    	return mysql_num_fields($result);
    }

    function insert_id(){
    	return mysql_insert_id($this->linkid);
    }

    function free_result(){
    	return mysql_free_result($this->linkid);
    }
	
	function escape_string($string)
    {
        if (PHP_VERSION >= '4.3')
        {
            return mysql_real_escape_string($string, $this->linkid);
        }
        else
        {
            return mysql_escape_string($string, $this->linkid);
        }
    }
    function error(){
    	return mysql_error($this->linkid);
    }

    function errno(){
    	return mysql_errno($this->linkid);
    }

    function close(){
    	return mysql_close($this->linkid);
    }

    function dbversion(){
    	return mysql_get_server_info($this->linkid);
    }

    function dbshow($err)
	{
    	if($err){
    		$info = "Error: ".$err;			
    	}else{
    		$info = "Errno: ".$this->errno()."<br/> Error: ".$this->error();
    	}
    	showmsg("Errno: Query error", $info);
    	//exit($info);
    }
    
	/**
	 * 执行添加记录操作
	 * @param $data 		要增加的数据，参数为数组。数组key为字段值，数组值为数据取值
	 * @param $table 		数据表
	 * @return boolean
	 */
	function insert($data, $table, $return_insert_id = false, $replace = false, $silent=0) {
		if(!is_array( $data ) || $table == '' || count($data) == 0) {
			return false;
		}
		
		$fielddata = array_keys($data);
		$valuedata = array_values($data);
		array_walk($fielddata, array($this, 'add_special_char'));
		array_walk($valuedata, array($this, '_escape_string'));
		
		$field = implode (',', $fielddata);
		$value = implode (',', $valuedata);

        $method = $replace?'REPLACE':'INSERT';
        $state = $this->query($method." INTO $table ($field) VALUES ($value)", $silent?'SILENT':'');
        if($return_insert_id && !$replace) {
            return $this->insert_id();
        }else {
            return $state;
        } 
	}
	
    
	/**
	 * 执行更新记录操作
	 * @param $data 		要更新的数据内容，参数可以为数组也可以为字符串，建议数组。
	 * 						为数组时数组key为字段值，数组值为数据取值
	 * 						为字符串时[例：`name`='kuaifan',`hits`=`hits`+1]。
	 *						为数组时[例: array('name'=>'kuaifan','password'=>'123456')]
	 *						数组可使用array('name'=>'+=1', 'base'=>'-=1');程序会自动解析为`name` = `name` + 1, `base` = `base` - 1
	 * @param $table 		数据表
	 * @param $where 		更新数据时的条件
	 * @return boolean
	 */
	function update($data, $table, $where = '', $silent=0) {
		if($table == '' or $where == '') {
			return false;
		}
		//
        if(empty($where)) {
            $where = '1';
        } elseif(is_array($where)) {
            foreach ($where as $key => $value) {
                $where .= $comma.'`'.$key.'`'.'=\''.$value.'\'';
                $comma = ' AND ';
            }
        }
		$where = ' WHERE '.$where;
		//
		$field = '';
		if(is_string($data) && $data != '') {
			$field = $data;
		} elseif (is_array($data) && count($data) > 0) {
			$fields = array();
			foreach($data as $k=>$v) {
				switch (substr($v, 0, 2)) {
					case '+=':
						$v = substr($v,2);
						if (is_numeric($v)) {
							$fields[] = $this->add_special_char($k).'='.$this->add_special_char($k).'+'.$this->_escape_string($v, '', false);
						} else {
							continue;
						}
						
						break;
					case '-=':
						$v = substr($v,2);
						if (is_numeric($v)) {
							$fields[] = $this->add_special_char($k).'='.$this->add_special_char($k).'-'.$this->_escape_string($v, '', false);
						} else {
							continue;
						}
						break;
					default:
						$fields[] = $this->add_special_char($k).'='.$this->_escape_string($v);
				}
			}
			$field = implode(',', $fields);
		} else {
			return false;
		}
		
        return $this->query("UPDATE ".($table)." SET ".$field.$where, $silent?"SILENT":"");
	}
    
	/**
	 * 对字段两边加反引号，以保证数据库安全
	 * @param $value 数组值
	 */
	function add_special_char(&$value) {
		if('*' == $value || false !== strpos($value, '(') || false !== strpos($value, '.') || false !== strpos ( $value, '`')) {
			//不处理包含* 或者 使用了sql方法。
		} else {
			$value = '`'.trim($value).'`';
		}
		if (preg_match("/\b(select|insert|update|delete)\b/i", $value)) {
			$value = preg_replace("/\b(select|insert|update|delete)\b/i", '', $value);
		}
		return $value;
	}
	
	/**
	 * 对字段值两边加引号，以保证数据库安全
	 * @param $value 数组值
	 * @param $key 数组key
	 * @param $quotation 
	 */
	function _escape_string(&$value, $key='', $quotation = 1) {
		$value = rtrim($value, '/\\');
		if ($quotation) {
			$q = '\'';
		} else {
			$q = '';
		}
		$value = $q.$value.$q;
		return $value;
	}
}
?>