Location: PHPKode > scripts > formAt > format/formAt.class.php
<?
/**
 * Web-form solution for PHP Developers
 * @author Javier Flores I. <hide@address.com>
 * @version 1.0
 * @package KX PHP CLASSES
*/



class formAt{

/**
* Error string prefix
* @access private
* @var string
*/
private $errorMsg = "ERROR AT: ";

/**
* Varchar max length in MYSQL
* @access private
* @var integer
*/
private $varcharMaxSize = 255;

/**
* Initial option for <select>
* @access private
* @var string
*/
private $selectIniLabel = "";

/**
* Don't start debug
* @access private
* @var boolean
*/
private $debug = false;

/**
* Enable default values for db-based fields
* @access private
* @var boolean
*/
private $defaults = true;

/**
* DB Link Identifier
* @access private
* @var integer
*/
private $dbLink;





/**
* Constructor
*/
function __construct($doConnect=true,$host="",$login="",$password="",$database=""){

	if($doConnect){
		$this->dbLink = mysql_connect($host,$login,$password);
		mysql_select_db($database,$this->dbLink);
	}
}


/**
* Close database connection, only if i get connected by this class
* @access public
* @return void
*/
public function closeDBConnection(){
	mysql_close($this->dbLink);
}




/**
* Change Debug status
* @access public
* @param boolean $status status boolean value
* @return void
*/
public function startDebug($status=true){
	$this->debug = $status;
}




/**
* Generate a TEXT or TEXTAREA field based on a table colum 
* @access public
* @param string $tb Database Table
* @param string $field Database Column
* @param string $value Field Value
* @param string $class CSS Style(s)
* @param string $type HTML object's type, 'text' | 'password', default 'text'
* @param string $extraParams Extra code for the object, for example Javascripts or style
* @param string $forcedName Force the HTML object's name
* @return string 
*/
public function genStrField($tb,$field,$value="",$class="",$type="text",$extraParams="",$forcedName=""){

	
	$ret = "";
	
	$query = "SELECT $field FROM $tb";
	
	$this->_exeQuery($query);
	$fieldLength = $this->_getFieldLength(0);
	
	if (!empty($forcedName)){
		$fieldName = $forcedName;
	}
	else{	
		$fieldName = $this->_getFieldName($fieldNumber);
	}
	
	if(empty($value)){
		if($this->defaults){
			$value = $this->_defaultValue($tb,$field);
		}
	}
	
	if ($fieldLength<=$this->varcharMaxSize){
		$ret = $this->addTHPInput($fieldName,$value,$type,$class,$fieldLength,$extraParams);
	}
	else{
		$ret = $this->addTextArea($fieldName,$value,$class,$extraParams);
	}
	
	return $ret;
		
}



/**
* Generate a  SELECT,CHECKBOX-SET or RADIO-SET basen on table
* @access public
* @param string $tb Databased Table
* @param string $fValue Database Column to use as value
* @param string $fLabel Database Column to use as label
* @param string $class CSS Style(s)
* @param string $type HTML object's type 'select' | 'checkbox' | 'radio', default 'select'
* @param string $extQuery Extra query string for filtering example: 'WHERE my_field LIKE "%web%"'
* @param array $selected Array that contains the selected(s) value(s) example array(1,"str"...)
* @param string $extraParams Extra code for the object, for example Javascripts or style
* @param integer $size Just in case the $type is 'select', to define the size of the select
* @param boolean $multiple Just in case the $type is 'select', to define if multiple selection is allowed
* @param string $forcedName Force the HTML object's name
* @return string 
*/
public function genCatalogueField($tb,$fValue,$fLabel,$class="",$type="select",$extQuery="",$selected=array(),$extraParams="",$size=1,$multiple=false,$forcedName=""){
	$ret = "";
	
	if(!is_array($selected)){
		$ret = "selected IS NOT AN ARRAY";
	}
	else{
	
		$query = "SELECT $fValue,$fLabel FROM $tb $extQuery";
		$this->_exeQuery($query);
		$ar = array();
		
			if (mysql_num_rows($this->result)){
				for ($i=0;$i<=mysql_num_rows($this->result)-1;$i++){
					$ar[$i]["value"] = $this->_fetchField($i,$fValue);
					$ar[$i]["label"] = $this->_fetchField($i,$fLabel);
				}
			}
			
			if (!empty($forcedName)){
				$idField = $forcedName;
			}
			else{
				$idField = $fValue;
			}
		
		switch ($type){
		case "select":
			$ret = $this->addSelectList($idField, $ar, $class, $selected, $extraParams, $size,$multiple);
		break;
		case "checkbox":
			$ret = $this->addCheckBox($idField, $ar,$class,$selected,$extraParams);
		break;
		case "radio":
			$ret = $this->addRadio($idField, $ar,$class,$selected[0], $extraParams);
		break;
		default:
			$ret = "INVALID FIELD TYPE, PLEASE USE 'select','radio' or 'checkbox'";
		break;
		}
	}	
	return $ret;	  
	
}




/**
* Generate a  SELECT,CHECKBOX-SET or RADIO-SET 'enum' or 'set' based on a table column
* @access public
* @param string $tb Database Table
* @param string $field Database Column
* @param string $class CSS Style
* @param string $type HTML object's type 'select' | 'checkbox' | 'radio', default 'select'
* @param array $selected Array that contains the selected(s) value(s) example array(1,"str"...) 
* @param string $extraParams Extra code for the object, for example Javascripts or style
* @param integer $size Just in case the $type is 'select', to define the size of the select
* @param boolean $multiple Just in case the $type is 'select', to define if multiple selection is allowed
* @param string $forcedName Force the HTML object's name
* @return string 
*/
public function genEnumSetField($tb,$field,$class="",$type="select",$selected=array(),$extraParams="",$size=1,$multiple=false,$forcedName=""){

	$prop = $this->_getEnumSet($tb,$field);
	
	if(!is_array($selected)){
		$ret = "selected IS NOT AN ARRAY";
	}
	else{
		
		if(count($selected)<=0){
			$selected = array($prop["default"]);
		}
		
		if (!empty($forcedName)){
			$field = $forcedName;
		}	
	
		switch($prop["type"]){
		
		case "enum":
			switch ($type){
			case "select":
				$ret = $this->addSelectList($field,$prop["options"], $class, $selected, $extraParams,$size);
			break;
			case "checkbox":
				$ret = "INVALID FIELD TYPE FOR A 'enum', PLEASE USE 'select' or 'radio'";
			break;
			case "radio":
				$ret = $this->addRadio($field,$prop["options"],$class,$selected[0], $extraParams);
			break;
			default:
				$ret = "INVALID FIELD TYPE, PLEASE USE 'select','radio' or 'checkbox'";
			break;
			
			}
				
		break;
		
		case "set":
			switch ($type){
			case "select":
				$ret = $this->addSelectList($field,$prop["options"], $class, $selected, $extraParams, $size,$multiple);
			break;
			case "checkbox":
				$ret = $this->addCheckBox($field,$prop["options"],$class,$selected,$extraParams);
			break;
			case "radio":
				$ret = "INVALID TYPE FOR A 'set', PLEASE USE 'select' or 'checkbox'";
			break;
			default:
				$ret = "INVALID FIELD TYPE, PLEASE USE 'select','radio' or 'checkbox'";
			break;
			}
	
		break;
		
		}
	
	}
	
	return $ret;

}




/**
* Set the first option label for the select size 1, the value will remain empty
* @access public
* @param string $str String
* @return void 
*/
public function setSelectIniLabel($str){//
  	$this->selectIniLabel = $str;
}


/**
* Set the object value to column default value or system variable in case the object value is not setted
* @access public
* @param boolean $boolean true | false
* @return void 
*/
public function defaults($boolean){
	$this->defaults = $boolean;
}



/**
* Generate a TEXT | HIDDEN | PASSWORD  object
* @access public
* @param string $idField HTML object's name
* @param string $value Object's value
* @param string $type HTML object's type 'text' | 'hidden' | 'password', default 'text'
* @param string $class CSS Style
* @param integer $maxlength In case of 'text' | 'password', maxlength of the object, default 100
* @param string $extraParams  Extra code for the object, for example Javascripts or style
* @return string 
*/
public function addTHPInput($idField, $value='', $type="text", $class="", $maxlength=100,$extraParams=""){
  

	switch ($type){
		
	case "text":
		$ret = '<input id="'.$idField.'" name="'.$idField.'"   maxlength="'.$maxlength.'" type="text" value="'.$value.'" '.$extraParams.' class="'.$class.'">';
	break;
	
	case "password":
        $ret = '<input id="'.$idField.'" name="'.$idField.'"  maxlength="'.$maxlength.'" type="password" value="'.$value.'" '.$extraParams.' class="'.$class.'">';
	break;
	
	case "hidden":
        $ret = '<input id="'.$idField.'" name="'.$idField.'"   type="hidden" value="'.$value.'" >';
		$maxlength = "-";
	break;	
		
	}
	
	if ($this->debug){
		$ret .= $this->_setDebug($idField,$value,$maxlength,$class,$extraParams);
	}
	
	return $ret;
	    
 }
  
  
 
/**
* Generate a SELECT object
* @access public
* @param string $idField HTML object's name
* @param array $ar Labels and Values for the list according this format :  $ar[0]['label'] = 'value1'; $ar[0]['value'] = '1' ...
* @param string $class CSS Style
* @param array $selected Array that contains the selected(s) value(s) example array(1,"apple"...) 
* @param string $extraParams Extra code for the object, for example Javascripts or style
* @param integer $size Size of the select
* @param boolean $multiple Just in case the $type is 'select', to define if multiple selection is allowed
* @return string 
*/
public function addSelectList($idField, $ar, $class="", $selected=array(), $extraParams="", $size=1,$multiple=false){
  	
	  if ($size>0){
	  	$SelSize = 'size="'.$size.'"';
	  }	
	  else{
	  	$SelSize = "";
	  }
	  
	  if ($multiple){
	  	$isMultiple = "multiple";
	  }
	  else{
	  	$isMultiple = "";
	  }
	
      $strRet = '<select id="'.$idField.'" name="'.$idField.'" '.$SelSize.' '.$isMultiple.' '.$extraParams.' class="'.$class.'">';
	  
	  if ($size<=1){
		 if (isset($this)){
			if(isset($this->selectIniLabel)){
				$strRet.= '<option value="" style="font-weight:bold">'.$this->selectIniLabel.'</option>';
				$this->selectIniLabel = "";
			}
		}
	  }
	  
      for($i=0; $i<count($ar); $i++){
	 	if (count($selected)>0){
			if (in_array($ar[$i]["value"],$selected)){
				$strRet.= '<option value="'.$ar[$i]["value"].'" selected>'.$ar[$i]["label"].'</option>';
			}
			else{
				$strRet.= '<option value="'.$ar[$i]["value"].'">'.$ar[$i]["label"].'</option>';
			}
		}
	  	else{
        	$strRet.= '<option value="'.$ar[$i]["value"].'">'.$ar[$i]["label"].'</option>';
		}
      }
      $strRet.= '</select>';
	  
	if ($this->debug){
		$strRet .= $this->_setDebug($idField,$selected,"-",$class,$extraParams);
	}

	  
	  
      return $strRet;
 }//
  
  
  
  
/**
* Generate a CHECKBOX-SET
* @access public
* @param string $idField HTML object's name
* @param array $ar Labels and Values for the set according this format :  $ar[0]['label'] = 'valor1'; $ar[0]['value'] = '1' ...
* @param string $class CSS Style for the label
* @param array $checked Array that contains the checked(s) value(s) example array(1,"str"...)
* @param string $extraParams Extra code for the object, for example Javascripts or style
* @return string 
*/ 
public function addCheckBox($idField, $ar, $class, $checked=array(), $extraParams=""){
  
    if($ar=='' || count($ar)==0){
      return false;
    }
    else{

      for($i=0; $i<count($ar); $i++){
			if (in_array($ar[$i]["value"],$checked)){
				$strRet .= '<label class="'.$classLabel.'" id='.$idField.'[]><input type="checkbox" id='.$idField.'[] name='.$idField.'[] value="'.$ar[$i]["value"].'" '.$extraParams.' '.$isProcess.' checked >'.$ar[$i]["label"].'</label><br>';
			}
			else{
				$strRet .= '<label class="'.$classLabel.'"><input type="checkbox" id='.$idField.'[] name='.$idField.'[] value="'.$ar[$i]["value"].'" '.$extraParams.' '.$isProcess.'>'.$ar[$i]["label"].'</label><br>';
			}
	  
      }
	  
	if ($this->debug){
		$strRet .= $this->_setDebug($idField,$checked,"-",$class,$extraParams);
	}

	  
      return $strRet;
    }
 }
  
  
  
  
/**
* Generate a RADIO-SET
* @access public
* @param string $idField HTML object's name
* @param array $ar Labels and Values for the set according this format :  $ar[0]['label'] = 'valor1'; $ar[0]['value'] = '1' ...
* @param string $class CSS Style for the label
* @param string $checked Checked Value
* @param string $extraParams Extra code for the object, for example Javascripts or style
* @return string 
*/  
public function addRadio($idField, $ar, $class="", $checked="", $extraParams=""){
  
    if($ar=='' || count($ar)==0){
      return false;
    }
    else{	
      for($i=0; $i<count($ar); $i++){
	  	if ($ar[$i]["value"] == $checked){
			$strRet .= '<label class="'.$class.'"><input type="radio" id="'.$idField.'" name="'.$idField.'" value="'.$ar[$i]["value"].'" '.$extraParams.' '.$isProcess.' checked > '.$ar[$i]["label"].'</label><br />';
		}
	  	else{
			$strRet .= '<label class="'.$class.'"><input type="radio" id='.$idField.' name="'.$idField.'" value="'.$ar[$i]["value"].'" '.$extraParams.' '.$isProcess.'> '.$ar[$i]["label"].'</label><br />';
		}
      }
	  
	if ($this->debug){
		$strRet .= $this->_setDebug($idField,$checked,"-",$class,$extraParams);
	}

	  
      return $strRet;
    }
 }
  
  
  
 
 /**
* Generate a TEXTAREA object
* @access public
* @param string $idField HTML object's name
* @param string $value Value
* @param string $class CSS Style
* @param string $extraParams Extra code for the object, for example Javascripts or style
* @return string 
*/ 
public function addTextArea($idField, $value="", $class="", $extraParams=""){
  
    if(empty($idField)){
      return false;
    }
    else{
      $strRet =  '<textarea id="'.$idField.'" name="'.$idField.'" class="'.$class.'" '.$extraParams.'>'.$value.'</textarea>';
	
	if ($this->debug){
		$strRet .= $this->_setDebug($idField,$value,"Long Text",$class,$extraParams);
	}
	
	return $strRet;
	  
    } 
 }





/**
* Generate a FILE INPUT object
* @access public
* @param string $idField HTML object's name
* @param string $class CSS Style
* @param string $extraParams Extra code for the object, for example Javascripts or style
* @return string 
*/ 


public function addUploadField($idField, $class, $extraParams=""){

	$strRet =  '<input type="file" id="'.$idField.'" name="'.$idField.'" class="'.$class.'" '.$extraParams.'>';
	
	if ($this->debug){
		$strRet .= $this->_setDebug($idField,"-","-",$class,$extraParams);
	}
	
	return $strRet;

}



/**
* query MYSQL
* @access private
* @param string $query Query string
* @return void 
*/ 
private function _exeQuery($query) {

	$this->query = $query;
	$this->result = mysql_query($query) or die ($this->errorMsg.'mysql() <br>'.$query." >> ".mysql_error());

}



/**
* Get the number of fields in the query
* @access private
* @return integer
*/ 
private function _getNumFields() {

	$fields = mysql_num_fields($this->result) or die ($this->errorMsg.'getNumFields()');
	return $fields;

}



/**
* Get field name in query
* @access private
* @param integer $fieldNumber Colum Index
* @return string
*/ 
private function _getFieldName($fieldNumber){

	$f_name = mysql_field_name($this->result,$fieldNumber) or die ($this->errorMsg.'getFieldName()');
	return $f_name;

}
 
 
  
/**
* Get the field length 
* @access private
* @param integer $fieldNumber Colum Index
* @return integer
*/ 
private function _getFieldLength($fieldNumber){

	$f_len = mysql_field_len($this->result,$fieldNumber) or die ($this->errorMsg.'getFieldLength');
	return $f_len;

}



/**
* Get the column's type
* @access private
* @param integer $fieldNumber Colum Index
* @return string 
*/ 
private function _getFieldType($fieldNumber){

	$f_type = mysql_field_type($this->result,$fieldNumber) or die ($this->errorMsg.'getFieldType()');
	return $f_type;

}



/**
* Fetch
* @access private
* @param integer $id Colum Index
* @return array
*/ 
private function _fetchRow($id) {

$data = mysql_data_seek($this->result,$id) or die ($this->errorMsg.'fetchRow()'.$this->query);
$row = mysql_fetch_array($this->result) or die ($this->errorMsg.'fetchRow()'.$this->query);

return $row;

}


/**
* Fetch one row
* @access private
* @param integer $numRow Row number
* @param string $fieldName Colum name
* @return string
*/ 
private function _fetchField($numRow,$fieldName){

	$row = $this->_fetchRow($numRow);
	return $row[$fieldName];

}




/**
* Num Rows in query
* @access private
* @return integer
*/ 
private function _getNumRows(){

	$rows = mysql_num_rows($this->result) or die ($this->errorMsg.'getNumRows()');
	return $rows;
	
} 



/**
* Get the options and default value in a given "enum / set" column
* @access private
* @param string $table Table
* @param string $field Column
* @return array
*/ 
private function _getEnumSet($table,$field){
    
	$this->_exeQuery("SELECT DATA_TYPE, COLUMN_TYPE FROM INFORMATION_SCHEMA.`COLUMNS` WHERE TABLE_NAME = '".$table."' AND COLUMN_NAME = '".$field."'");
	
    if($this->_getNumRows()>0){
        $row = $this->_fetchRow(0);
        $opts = explode("','", preg_replace("/(enum|set)\('(.+?)'\)/","\\2", $row[1]));
		for($i=0;$i<=count($opts)-1;$i++){
			$options[$i]["label"] = $opts[$i];
			$options[$i]["value"] = $opts[$i];
		}
		$type = $row[0]; 
		$default = $this->_defaultValue($table,$field);
    	
		return  array(
			"type" => $type,
			"options" => $options,
			"default" => $default
		);
	}
	else{
		return array();
	} 
	
	
}




/**
* Get the default value of a colum or the variable value in server variables
* @access private
* @param string $table Table
* @param string $field Column
* @return string
*/ 
private function _defaultValue($table,$field){

	$this->_exeQuery("SELECT COLUMN_DEFAULT,DATA_TYPE,NUMERIC_PRECISION,NUMERIC_SCALE FROM INFORMATION_SCHEMA.`COLUMNS` WHERE TABLE_NAME = '".$table."' AND COLUMN_NAME = '".$field."'");
	
	if($this->_getNumRows()>0){
        $row = $this->_fetchRow(0);
		if(!empty($row[0])){
			return $row[0];
		}
		else{
			switch($row[1]){
				
				case "date": case "datetime": case "time":
					return date(str_replace("%","",$this->_variableValue($row[1]."_format")));
				break;
				
				case "year":
					return date("Y");	
				break;
				
				case "tinyint": case "smallint": case "mediumint": case "bigint": case "int": case "integer": 
					return "0";
				break;
				
				case "float": case "double": case "decimal":
				
					$ints = ($row[2]-$row[3]);
					for($i=0;$i<=$ints-1;$i++){
						$enteros .= "0";
					}
					for($i=0;$i<=$row[3]-1;$i++){
						$decimales .= "0";
					}
					
					return $enteros.".".$decimales;
					
					
				break;
				
				default:
					return "";
				break;
				
			}
		}
    }
}


/**
* Get a variable value in server
* @access private
* @param string $Variable_name Name of the variable
* @return string
*/ 
private function _variableValue($Variable_name){
	
	$this->_exeQuery("SHOW VARIABLES WHERE Variable_name='".$Variable_name."'");
	$row = $this->_fetchRow(0);
	return $row[1];
	

}


/**
* Prints debugging
* @access private
* @param string $fieldName Element Name
* @param string $values Values 
* @param integer $fieldLength Length
* @param string $class CSS Style
* @param string $extraParams Extra Parameters
* @return string
*/ 
private function _setDebug($fieldName,$values,$fieldLength,$class,$extraParams){
	
	$ret = "<div style='border:solid 1px #ccc'>&uarr;<br /><span style='color:red;font-size:12px'>DEBUG ACTIVE ...</span><br /><small>";
	$ret .= "<strong>Name:</strong> ".$fieldName."<br><strong>Length:</strong> ".$fieldLength."<br><strong>Class(es):</strong> ".$class."<br><strong>Extra Params:</strong> ".$extraParams;
	$ret .= "<br /><strong>Value(s) / Selected(s):</strong> ";
	if(is_array($values)){
		$ret .= "<br /><pre>";
		while(list($k,$v)=each($values)){
			$ret .= "	[".$k."] = ".$v."<br />";
		}
		$ret .= "</pre>";
	}
	else{
		$ret .= $values;
	}
	$ret .= "</small></div>";
	
	
	return $ret;

}


  
}

?>
Return current item: formAt