<?php
	class MysqlWrapperISP {
		private static $mysql_server_name="192.168.0.122:3306"; //数据库服务器名称
		private static $mysql_username="root"; // 连接数据库用户名
		private static $mysql_password="sjgj2508"; // 连接数据库密码
		private static $mysql_database="ipv6_enabled_isp_db"; // 数据库的名字
		
		public static function exist(){
			$attr = func_get_args();
			$c = self::count($attr);
			if ($c > 0){
				return TRUE;
			}else{
				return FALSE;
			}
		}
		
		public static function find(){
			if((func_num_args() == 1) && is_array(func_get_arg(0))){
				$attr =func_get_arg(0);
				$strsql = self::a2s($attr);
			}elseif(func_num_args() == 1 && is_string(func_get_arg(0))){
				$strsql = "select * from ".func_get_arg(0);
			}
			else{
				$attr = func_get_args();
				$strsql = self::a2s($attr);
			}
			return self::exec($strsql);
		}
		
		public static function find_first(){
			$attr = func_get_args();
			$rows=self::find($attr);
			return $rows[0];
		}
		
		public static function count(array $attr){
			$strsql = self::a2s($attr);
			try {
				return count(self::exec($strsql));
			}catch(Exception $e){
				return 0;
			}
		}
		
		public static function query(){
			if((func_num_args() == 1) && is_array(func_get_arg(0))){
				$attr =func_get_arg(0);
				$strsql = self::a2s($attr);
			}elseif(func_num_args() == 1 && is_string(func_get_arg(0))){
				$strsql = func_get_arg(0);
			}
			else{
				$attr = func_get_args();
				$strsql = self::a2s($attr);
			}
			
			return self::exec($strsql);
		}
		
		private static function wrap2array($result){
			$wrapped = array();
			while ($row=mysql_fetch_array($result)){
				array_push($wrapped,$row);
			}
			if (count($wrapped) == 0){
				throw new Exception("No such record in DB");
			}
			return $wrapped;
		}
		
		public static function exec($strsql){
			ini_set("display_errors","0");
			$mydb=mysql_connect(self::$mysql_server_name, self::$mysql_username, self::$mysql_password);
			if(!$mydb){
				throw new Exception("Connection error".mysql_error());
			}else {
				mysql_select_db(self::$mysql_database,$mydb);
				$result=mysql_query($strsql );
				if($result != FALSE){
					if(is_bool($result)){
						return TRUE;
					}else{
						$rows = self::wrap2array($result);
						mysql_free_result($result);
					}
				}else{
					throw new Exception("Sql condition is error".mysql_error());
				}
				mysql_close(); 
				return $rows;
			}
		}
		
		private static function a2s($attr){
			$strcond = $attr[1];
			$table=$attr[0];
			$length = count($attr);
			$array = explode("?", $strcond);
			$result="select * from $table where ";
			if ($length != count($array) + 1){
				throw new Exception("Bad Condition");
			}
			for($i = 2; $i <= $length; $i ++){
				if ( $i != $length) {
					$result = $result.$array[$i-2].'\''.$attr[$i].'\'';
				}else{
					$result = $result.$array[$i-2];
				}
			}
			return $result;
		}
	}
