<?php
class sqlclass
{
	var $tablename;
	var $fieldvalue;
	var $fieldname;
	var $updatefieldname;
	var	$updatefieldvalue;
	var $condition;
	var $limit;
	private $general;
	 
	function __construct()
	{
	
			date_default_timezone_set("Asia/Kolkata");
			$this->now		= date("Y-m-d");
			$this->date		= date("Y-m-d H:i:s");
			
	}
		
	function __destruct()
	{
			@$this->db->dbClose();
	}
	//check duplicate fieldvalue when adding feilds to a table
	function valueexists()
	{
		$tablename=$this->tablename;
		$fieldname=$this->fieldname;
		$fieldvalue=$this->fieldvalue;
		$sql="select * from ".$tablename." where ".$fieldname."='".$fieldvalue."'";
		
		$row	= $this ->readValue($sql);
		return $row;
	}
	//check duplicate fieldvalue when  feilds  update the table
	function updatevalueexists()
	{
		$tablename=$this->tablename;
		$fieldname=$this->fieldname;
		$fieldvalue=$this->fieldvalue;
		//$updatefieldname=$this->updatefieldname;
		$updatefieldvalue=$this->updatefieldvalue;
		
		//$sql="update ".$tablename.$fieldname." set  where ".$updatefieldvalue;
		
		$sql="select * from ".$tablename." where ".$fieldname."='".$fieldvalue."' and  ".$updatefieldvalue;
		$row	= $this ->db ->readValue($sql);
		return $row;
	}
	//-----------------------------------------------------------------//
	//Add the values into a table
	function AddTable()
	 {
	 	$tablename=$this->tablename;
		$fieldname=$this->fieldname;
		$fieldvalue=$this->fieldvalue;
		$date=date("Y-m-d");
		$sql	=	"insert into ".$tablename.$fieldname." values(".$fieldvalue.")"; 
		$res	    =   $this->setQuery($sql);
		return 1;
		
	}
	//Update the Values
	function UpdateTable()
	{
		$tablename=$this->tablename;
		$fieldvalue=$this->fieldvalue;
	    $updatefieldname=$this->updatefieldname;
		$updatefieldvalue=$this->updatefieldvalue;
		$updatefieldtype=$this->updatefieldtype;
	 	$sql="update ".$tablename." set ".$updatefieldname."=".$updatefieldvalue. "where ".$updatefieldtype. "=".$fieldvalue;
		//echo $sql="update ".$tablename.$fieldname." set  where ".$updatefieldvalue;
		$res	    =   $this->setQuery($sql);
		return 2;
	}
	function UpdateTable_new()
	{
		$tablename=$this->tablename;
		$values=$this->updatefieldvalue;
		$condn=$this->updatefieldtype;
	 	$sql="update ".$tablename." set ".$values.$condn;
		//echo $sql="update ".$tablename.$fieldname." set  where ".$updatefieldvalue;
		$res	    =   $this->setQuery($sql);
	}
	//Fetch the Values
	function SelectTable()
	{
		$tablename=$this->tablename;
		$fieldvalue=$this->fieldvalue;
		$condition=$this->condition;
		$limit=$this->limit;
		$sql="select ".$fieldvalue." from ".$tablename.$condition.$limit;
		$res	    =   $this->readValue($sql);
		return $res;
	}
	
	function SelectTable1()
	{
		$tablename1=$this->tablename1;
		$fieldvalue1=$this->fieldvalue1;
		$condition1=$this->condition1;
		$limit=$this->limit;
		$sql="select ".$fieldvalue1." from ".$tablename1.$condition1.$limit;
		$res	    =   $this->readValue($sql);
		return $res;
	}
	function SelectTable_qry()
	{
		$tablename=$this->tablename;
		$fieldvalue=$this->fieldvalue;
		$condition=$this->condition;
		$limit=$this->limit;
		$sql="select ".$fieldvalue." from ".$tablename.$condition.$limit;
		$res	    =   mysql_query($sql);
		return $res;
	}
	function SelectTableNum()
	{
		$tablename=$this->tablename;
		$fieldvalue=$this->fieldvalue;
		$condition=$this->condition;
		$num=0;
		$sql="select ".$fieldvalue." from ".$tablename.$condition;
		$res	    =   mysql_query($sql);
		if($res){
		$num=mysql_num_rows($res);
		}
		return $num;
	}
	//---------------------------------------------//
	function readValue($Query)
	{
		$Row	=	array();
		$Rs		=	@mysql_query($Query);	
		
		if(!$Rs) {
			$this->ErrorInfo	=	mysql_error();
			echo $this->ErrorInfo;
			exit;
			return $Row;	 
		} else {
			$Row	=	@mysql_fetch_array($Rs);
			@mysql_free_result($Rs);
			//print_r($Row);//exit;
			return $Row;  		
		}
	}
	function setQuery($Query)
	{
		$ExecStatus		=	@mysql_query($Query);
		if($ExecStatus	===	FALSE) {
		
			$this->ErrorInfo	=	mysql_error();
			echo $this->ErrorInfo;
		exit;
			return FALSE;
		} else {
			return $ExecStatus;
		} 
	}
	function validateFields($fields, $rules)
	{ 
	//print_r($fields);
	  $errors = array();
	  
	  // loop through rules
	  for ($i=0; $i<count($rules); $i++)
	  {
		// split row into component parts 
		$row = explode(",", $rules[$i]);
		
		// while the row begins with "if:..." test the condition. If true, strip the if:..., part and 
		// continue evaluating the rest of the line. Keep repeating this while the line begins with an 
		// if-condition. If it fails any of the conditions, don't bother validating the rest of the line
		$satisfies_if_conditions = true;
		while (preg_match("/^if:/", $row[0]))
		{
		  $condition = preg_replace("/^if:/", "", $row[0]);
	
		  // check if it's a = or != test
		  $comparison = "equal";
		  $parts = array();
		  if (preg_match("/!=/", $condition))
		  {
			$parts = explode("!=", $condition);
			$comparison = "not_equal";
		  }
		  else 
			$parts = explode("=", $condition);
	
		  $field_to_check = $parts[0];
		  $value_to_check = $parts[1];
		  
		  // if the VALUE is NOT the same, we don't need to validate this field. Return.
		  if ($comparison == "equal" && $fields[$field_to_check] != $value_to_check)
		  {
			$satisfies_if_conditions = false;
			break;
		  }
		  else if ($comparison == "not_equal" && $fields[$field_to_check] == $value_to_check)
		  {
			$satisfies_if_conditions = false;
			break;      
		  }
		  else 
			array_shift($row);    // remove this if-condition from line, and continue validating line
		}
	
		if (!$satisfies_if_conditions)
		  continue;
	
	
		$requirement = $row[0];
		$field_name  = $row[1];
	
		// depending on the validation test, store the incoming strings for use later...
		if (count($row) == 6)        // valid_date
		{
		  $field_name2   = $row[2];
		  $field_name3   = $row[3];
		  $date_flag     = $row[4];
		  $error_message = $row[5];
		}
		else if (count($row) == 4)     // same_as
		{
		  $field_name2   = $row[2];
		  $error_message = $row[3];
		}
		else
		  $error_message = $row[2];    // everything else!
	
	
		// if the requirement is "length=...", rename requirement to "length" for switch statement
		if (preg_match("/^length/", $requirement))
		{
		  $length_requirements = $requirement;
		  $requirement         = "length";
		}
	
		// if the requirement is "range=...", rename requirement to "range" for switch statement
		if (preg_match("/^range/", $requirement))
		{
		  $range_requirements = $requirement;
		  $requirement        = "range";
		}
	
	
		// now, validate whatever is required of the field
		switch ($requirement)
		{
		  case "required":
			if (!isset($fields[$field_name]) || trim($fields[$field_name]) == "")
			  $errors[] = $error_message;
			break;
	
		  case "digits_only":       
			if (isset($fields[$field_name]) && preg_match("/\D/", $fields[$field_name]))
			  $errors[] = $error_message;
			break;
			
			case "not_zero":       
			if (isset($fields[$field_name]) && ($fields[$field_name]==0))
			  $errors[] = $error_message;
			break;
		
		  case "decimals_only":
		 		 if (! preg_match('/^-?\d*\.?\d+$/',$fields[$field_name])) 	
		  	 		 $errors[] = $error_message ;
					break;
	
		  case "letters_only": 
			if (isset($fields[$field_name]) && preg_match("/[^a-zA-Z]/", $fields[$field_name]))
			  $errors[] = $error_message;
			break;
			
			/* case "url":
				if (!preg_match('|^http(s)?://[a-z0-9-]+(\.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $fields[$field_name]))
					  $errors[] = $error_message;
				break;*/
				
			 case "url":
				if (!preg_match('|^http(s)?://[a-z0-9-]+(\.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $fields[$field_name]))
				{
					 if (!preg_match('/http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/', $fields[$field_name])){
					 
					   if (!preg_match('!^((ftp|(http(s)?))://)?(www)(\.?([a-z0-9-]+))+\.[a-z]{2,6}(:[0-9]{1,
> 5})?(/[a-zA-Z0-9.,;\?|\'+&%\$#=~_-]+)*$!i', $fields[$field_name])){
					    
					  		$errors[] = $error_message;
							
						}
					  }
				}
				break;
	
		  // doesn't fail if field is empty
		  case "valid_email":
			$regexp="/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";     
			if (isset($fields[$field_name]) && !empty($fields[$field_name]) && !preg_match($regexp, $fields[$field_name]))
			  $errors[] = $error_message;
			break;
	
		  case "length":
			$comparison_rule = "";
			$rule_string     = "";
	
			if      (preg_match("/length=/", $length_requirements))
			{
			  $comparison_rule = "equal";
			  $rule_string = preg_replace("/length=/", "", $length_requirements);
			}
			else if (preg_match("/length>=/", $length_requirements))
			{
			  $comparison_rule = "greater_than_or_equal";
			  $rule_string = preg_replace("/length>=/", "", $length_requirements);
			}
			else if (preg_match("/length<=/", $length_requirements))
			{
			  $comparison_rule = "less_than_or_equal";
			  $rule_string = preg_replace("/length<=/", "", $length_requirements);
			}
			else if (preg_match("/length>/", $length_requirements))
			{
			  $comparison_rule = "greater_than";
			  $rule_string = preg_replace("/length>/", "", $length_requirements);
			}
			else if (preg_match("/length</", $length_requirements))
			{
			  $comparison_rule = "less_than";
			  $rule_string = preg_replace("/length</", "", $length_requirements);
			}
	
			switch ($comparison_rule)
			{
			  case "greater_than_or_equal":
				if (!(strlen($fields[$field_name]) >= $rule_string))
				  $errors[] = $error_message;
				break;
			  case "less_than_or_equal":
				if (!(strlen($fields[$field_name]) <= $rule_string))
				  $errors[] = $error_message;
				break;
			  case "greater_than":
				if (!(strlen($fields[$field_name]) > $rule_string))
				  $errors[] = $error_message;
				break;
			  case "less_than":
				if (!(strlen($fields[$field_name]) < $rule_string))
				  $errors[] = $error_message;
				break;
				
			
			
			  case "equal":
				// if the user supplied two length fields, make sure the field is within that range
				if (preg_match("/-/", $rule_string))
				{
				  list($start, $end) = split("-", $rule_string);
				  if (strlen($fields[$field_name]) < $start || strlen($fields[$field_name]) > $end)
					$errors[] = $error_message;
				}
				// otherwise, check it's EXACTLY the size the user specified 
				else
				{
				  if (strlen($fields[$field_name]) != $rule_string)
					$errors[] = $error_message;
				}     
				break;       
			}
			break;
	
		  case "range":
			$comparison_rule = "";
			$rule_string     = "";
	
			if      (preg_match("/range=/", $range_requirements))
			{
			  $comparison_rule = "equal";
			  $rule_string = preg_replace("/range=/", "", $range_requirements);
			}
			else if (preg_match("/range>=/", $range_requirements))
			{
			  $comparison_rule = "greater_than_or_equal";
			  $rule_string = preg_replace("/range>=/", "", $range_requirements);
			}
			else if (preg_match("/range<=/", $range_requirements))
			{
			  $comparison_rule = "less_than_or_equal";
			  $rule_string = preg_replace("/range<=/", "", $range_requirements);
			}
			else if (preg_match("/range>/", $range_requirements))
			{
			  $comparison_rule = "greater_than";
			  $rule_string = preg_replace("/range>/", "", $range_requirements);
			}
			else if (preg_match("/range</", $range_requirements))
			{
			  $comparison_rule = "less_than";
			  $rule_string = preg_replace("/range</", "", $range_requirements);
			}
			
			switch ($comparison_rule)
			{
			  case "greater_than":
				if (!($fields[$field_name] > $rule_string))
				  $errors[] = $error_message;
				break;
			  case "less_than":
				if (!($fields[$field_name] < $rule_string))
				  $errors[] = $error_message;
				break;
			  case "greater_than_or_equal":
				if (!($fields[$field_name] >= $rule_string))
				  $errors[] = $error_message;
				break;
			  case "less_than_or_equal":
				if (!($fields[$field_name] <= $rule_string))
				  $errors[] = $error_message;
				break;
			  case "equal":
				list($start, $end) = explode("-", $rule_string);
	
				if (($fields[$field_name] < $start) || ($fields[$field_name] > $end))
				  $errors[] = $error_message;
				break;
			}
			break;
			
		  case "same_as":
			if ($fields[$field_name] != $fields[$field_name2])
			  $errors[] = $error_message;
			break;
	
		  case "valid_date":
			// this is written for future extensibility of isValidDate function to allow 
			// checking for dates BEFORE today, AFTER today, IS today and ANY day.
			$is_later_date = false;
			if    ($date_flag == "later_date")
			  $is_later_date = true;
			else if ($date_flag == "any_date")
			  $is_later_date = false;
	
			if (!is_valid_date($fields[$field_name], $fields[$field_name2], $fields[$field_name3], $is_later_date))
			  $errors[] = $error_message;
			break;
	
		case "date_validate":
			// this is written for future extensibility of isValidDate function to allow 
			// checking for dates BEFORE today, AFTER today, IS today and ANY day.
			$is_later_date = false;
			if    ($date_flag == "later_date")
			  $is_later_date = true;
			else if ($date_flag == "any_date")
			  $is_later_date = false;
			$dt_array	= explode('-',$fields[$field_name]);
			if (!is_valid_date($dt_array[0],$dt_array[1], $dt_array[2], $is_later_date))
			  $errors[] = $error_message;
			break;
			
		case "is_alpha":
			if (preg_match('/[^A-Za-z0-9]/', $fields[$field_name]))
			  $errors[] = $error_message; 
			break;
		 case "password":	
				if(strstr($fields[$field_name],' '))
					 $errors[] = "could not allow space in password";
				else if(strlen($fields[$field_name])<4)
					  $errors[] = $error_message;
				break;    
		  default:
			die("Unknown requirement flag in validateFields(): $requirement");
			break;
		}
	  }
	  
	  return $errors;
	}
	
	
	
	
	
function number_to_words ($x)
{
     global $nwords;
     if(!is_numeric($x))
     {
         $w = '#';
     }else if(fmod($x, 1) != 0)
     {
         $w = '#';
     }else{
         if($x < 0)
         {
             $w = 'minus ';
             $x = -$x;
         }else{
             $w = '';
         }
         if($x < 21)
         {
             $w .= $nwords[$x];
         }else if($x < 100)
         {
             $w .= $nwords[10 * floor($x/10)];
             $r = fmod($x, 10);
             if($r > 0)
             {
                 $w .= ' '. $nwords[$r];
             }
         } else if($x < 1000)
         {
		
             	$w .= $nwords[floor($x/100)] .' hundred';
             $r = fmod($x, 100);
             if($r > 0)
             {
                 $w .= ' '. number_to_words($r);
             }
         } else if($x < 1000000)
         {
         	$w .= number_to_words(floor($x/1000)) .' thousand';
             $r = fmod($x, 1000);
             if($r > 0)
             {
                 $w .= ' ';
                 if($r < 100)
                 {
                     $w .= ' ';
                 }
                 $w .= number_to_words($r);
             }
         } else {
             $w .= number_to_words(floor($x/1000000)) .' million';
             $r = fmod($x, 1000000);
             if($r > 0)
             {
                 $w .= ' ';
                 if($r < 100)
                 {
                     $word .= ' ';
                 }
                 $w .= number_to_words($r);
             }
         }
     }
     return $w;
}


function ExecuteSQL($query){
		
		$this->lastQuery 	= $query;
		if($this->result 	= mysql_query($query, $this->databaseLink)){
			$this->records 	= @mysql_num_rows($this->result);
			
			$this->affected	= @mysql_affected_rows($this->databaseLink);

			if($this->records > 0){
				$this->ArrayResults();
				return $this->arrayedResult;
			}else{
				return true;
			}

		}else{
			$this->lastError = mysql_error($this->databaseLink);
			return false;
		}
	}
          
		  
function fetchQuery($query){
	
	$a=0;
	$results = mysql_query($query)or dir(mysql_error());

	while ($rows = mysql_fetch_assoc($results))
	$result[$a++]=$rows;
	
	 return $result;
}  
		  
		    
        function fetchAll($from, $where='', $orderBy='', $limit='', $like=false, $operand='AND',$cols='*'){
            
            if(trim($from) == ''){
			return false;
		}

		$query = "SELECT {$cols} FROM `{$from}` WHERE ";

		if(is_array($where) && $where != ''){
			// Prepare Variables
			$where = $this->SecureData($where);

			foreach($where as $key=>$value){
				if($like){
					//$query .= '`' . $key . '` LIKE "%' . $value . '%" ' . $operand . ' ';
					$query .= "`{$key}` LIKE '%{$value}%' {$operand} ";
				}else{
					//$query .= '`' . $key . '` = "' . $value . '" ' . $operand . ' ';
					$query .= "`{$key}` = '{$value}' {$operand} ";
				}
			}

			$query = substr($query, 0, -(strlen($operand)+2));

		}else{
			$query = substr($query, 0, -7);
		}

		if($orderBy != ''){
			$query .= ' ORDER BY ' . $orderBy;
		}

		if($limit != ''){
			$query .= ' LIMIT ' . $limit;
		}
		//echo $query;

               //print_r($new);
                $results= mysql_query($query);
                
                $a=0;
			$result=array();
				
              while ($rows = mysql_fetch_array($results))
                   $result[$a++]=$rows;
				   
              return $result;
              }
                

          function getDaysInBetween($start, $end) {
     // Vars  
    $start = strtotime($start);
	$end = strtotime($end);
	$days_between = ceil(abs($end - $start) / 86400);
     // Return days  
     return $days_between;  
    } 	
	
	
	
	
}
  
	//number to words
//----------------------------------------------------//
$nwords = array(  "", "one", "two", "three", "four", "five", "six", 
	      	  "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", 
	      	  "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", 
	     	  "nineteen", "twenty", 30 => "thirty", 40 => "fourty",
                     50 => "fifty", 60 => "sixty", 70 => "seventy", 80 => "eigthy",
                     90 => "ninety" );



 
?>