<?php
/**
 * MySQL数据库类，出错时输出JSON
 * Created:	2011-12-25
 * 
 * @author Jumbo
 * @copyright Copyright Wolfsoft Studio. 2011, Jumbo
 * @version 1.0
 */
 
 
/**
 * MySQL数据库类，封装了对MySQL数据库的连接和query操作，出错时输出JSON
 * Created:	2011-12-25
 */
class Database{
	var $dblink;
	var $affected_rows = 0;
	var $sql; //for debug
	var $dbhost;
	var $dbuser;
	var $dbpw;
	var $dbname;
	
	function __get($name){
		return $this->$name;
	}
	
	function __set($name, $value){
		$this->$name = $value;
	}
	
	function __construct($dbhost, $dbuser, $dbpw, $dbname="") {
		$this->$dbhost = $dbhost;
		$this->$dbuser = $dbuser;
		$this->$dbpw = $dbpw;
		$this->$dbname = $dbname;
		
		if(function_exists('mysqli_connect')){
			$this->dblink = new mysqli($dbhost, $dbuser, $dbpw);
			
			if(@mysqli_connect_errno())
				die($this->__error_json(@mysqli_connect_errno(), @mysqli_connect_error()));
				
			mysqli_query($this->dblink, "SET NAMES UTF8");
			mysqli_query($this->dblink, "SET CHARACTER_SET_CLIENT=UTF8");
			mysqli_query($this->dblink, "SET CHARACTER_SET_RESULTS=UTF8");
			mysqli_query($this->dblink, "SET time_zone = '+8:00'");
			
			if($dbname){
				if(!@mysqli_select_db($this->dblink, $dbname))
					die($this->__error_json(@mysqli_errno($this->dblink), @mysqli_error($this->dblink)));
			}
		}
		else {
			$this->dblink = @mysql_connect($dbhost, $dbuser, $dbpw)
				or die($this->__error_json(@mysql_errno(), @mysql_error()));
				
			mysql_query("SET NAMES 'utf8'", $this->dblink);
			mysql_query("SET CHARACTER_SET_CLIENT=utf8", $this->dblink);
			mysql_query("SET CHARACTER_SET_RESULTS=utf8", $this->dblink);
			mysql_query("SET time_zone = '+8:00'", $this->dblink);
			
			if($dbname){
				@mysql_select_db($dbname, $this->dblink);
			}
		}
		
	}
	
	function database($dbhost, $dbuser, $dbpw, $dbname="") {
		$this->__construct($dbhost, $dbuser, $dbpw, $dbname);
	}
	
	function query($sql) {
		$this->sql = $sql;//for debug
		if(function_exists('mysqli_query')){
			$result = @mysqli_query($this->dblink, $sql);
			
			if($result===FALSE){
				die($this->__error_json(@mysqli_errno($this->dblink), @mysqli_error($this->dblink)));
			}
			
			if(strpos(strtolower(substr(ltrim($sql),0,6)),'select') === FALSE){
				$this->affected_rows = @mysqli_affected_rows($this->dblink);
				return $result;
			}
			else {
				return (new DatabaseResult($result));
			}
		}
		else {
			if(!@mysql_ping( $this->dblink )){
				@mysql_close($this->dblink);
				$this->dblink = @mysql_connect($this->dbhost,$this->dbuser,$this->dbpw);
				@mysql_select_db($this->dbname,$this->dblink);
			}
			
			$result = @mysql_query($sql, $this->dblink);
			
			if($result===FALSE){
				die($this->__error_json(@mysql_errno($this->dblink), @mysql_error($this->dblink)));
			}
			
			if(strpos(strtolower(substr(ltrim($sql),0,6)),'select') === FALSE){
				$this->affected_rows = @mysql_affected_rows($this->dblink);
				return $result;
			}
			else {
				return (new DatabaseResult($result));
			}
		}
	}
	
	function insert_id() {
		return function_exists('mysqli_insert_id') ? @mysqli_insert_id($this->dblink) : @mysql_insert_id($this->dblink);
	}
	
	function close() {
		if(function_exists('mysqli_close'))
			@mysqli_close($this->dblink);
		else 
			@mysql_close($this->dblink);
	}
	
	function __error_json($code, $description) {
		$msg = '数据库出错：<br>错误码：'.$code.'<br>错误描述：'.$description;
		$msg .= '<br>SQL:'.$this->sql;//for debug
		return '{"success":false, "msg": "'.$msg.'"}';
	}
	
}

/**
 * 数据库结果类：封装了对MySQL的结果集的操作，提供了将结果集转化为JSON
 */
class DatabaseResult{
	var $result;
	var $num_rows;
	
	function __get($name){
		return $this->$name;
	}
	
	function __set($name, $value){
		$this->$name = $value;
	}
	
	function __construct($rs){
		$this->result = $rs;
		$this->num_rows = function_exists('mysqli_num_rows') ? @mysqli_num_rows($rs) : @mysql_num_rows($rs);
	}
	
	function DatabaseResult($rs) {
		$this->__construct($rs);
	}
	
	function fetch_assoc() {
		return function_exists('mysqli_fetch_assoc') ? @mysqli_fetch_assoc($this->result) : @mysql_fetch_assoc($this->result);
	}
	
	function fetch_row() {
		return function_exists('mysqli_fetch_row') ? @mysqli_fetch_row($this->result) : @mysql_fetch_row($this->result);
	}
	
	function fetch_array($asso = MYSQLI_ASSOC) {
		return function_exists('mysqli_fetch_array') ? @mysqli_fetch_array($this->result, $asso) : @mysql_fetch_array($this->result, $asso);
	}
	
	function fetch_field(){
		return function_exists('mysqli_fetch_field') ? @mysqli_fetch_field($this->result) : @mysqli_fetch_field($this->result);
	}
	
	function free() {
		return function_exists('mysqli_free_result') ? @mysqli_free_result($this->result) : @mysql_free_result($this->result);
	}
	
	/**
	 * 将结果集转换成JSON并返回。
	 * 注意：数据库里的字符串应该是经过了addslashes处理的，否则有可能有问题。
	 */
	function to_json() {
		if($this->num_rows == 0) return null;
		$json = "";
		if($this->num_rows > 1) $json .= "[";
		while ($row = $this->fetch_assoc()){
			$r = "{";
			foreach ( $row as $field => $value){
				$r .= '"'.$field.'":"'.$value.'", ';
			}
			if(strlen($r)>2) $r = substr($r, 0, strlen($r)-2);
			$r .= "}";
			if(strlen($r)>2) $json .= $r. ", ";
		}
		if(strlen($json)>2) $json = substr($json, 0, strlen($json)-2);
		if($this->num_rows > 1) $json .= "]";
		return $json;
	}
}
?>
