<?php
class Master {
	private $hasQuotes, $PRIVATE_KEY, $TABLE_NAME;
	public function __construct($ID){
		global $con;
		
		//
		//	Private Key
		//
		$this->PRIVATE_KEY = "ID";
		//
		// Table name
		//
		$this->TABLE_NAME = "table name";
		//
		// Get Table Column and add to object.
		//
		$query = "SELECT * FROM `{$this->TABLE_NAME}` WHERE `{$this->PRIVATE_KEY}` = $ID";
		$result = mysqli_query($con, $query);
		$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
		foreach($row as $key => $value){
				$this->$key = $value;
		}
		//
		// Get Columns Names and either if they need quotes in a query or not.
		//
		$this->hasQuotes = [];
		$query = "SHOW COLUMNS FROM `{$this->TABLE_NAME}`";
		$result = mysqli_query($con,$query);
		while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
			if(stripos($row['Type'], "int") === 0 || stripos($row['Type'], "double") === 0 || stripos($row['Type'], "tinyint") === 0 || stripos($row['Type'], "numeric") === 0 || stripos($row['Type'], "double") === 0 || stripos($row['Type'], "decimal") === 0 || stripos($row['Type'], "float") === 0 || stripos($row['Type'], "bigint") === 0 || stripos($row['Type'], "real") === 0 || stripos($row['Type'], "bool") === 0){
				$this->hasQuotes[$row['Field']] = false;
			}else{
				$this->hasQuotes[$row['Field']] = true;
			}
		}
	}
	//
	// Function to create a "column = value" string usable by mysql query;
	//
	private function saveString($Column, $Value){
		
		if(is_null($Value)){
			$returnValue = "NULL";	
		}else{
			$returnValue = ($this->hasQuotes[$Column])?"'$Value'":"$Value";	
		}
		return " `$Column` = $returnValue ";
	}
	//
	// function to save all the values in the object to the table.
	//
	public function save(){
		global $con;
		
		$query = "UPDATE `{$this->TABLE_NAME}` SET ";
		$saveQuery = [];
		foreach($this->hasQuotes as $fieldName => $quotes){
			if($fieldName != $this->PRIVATE_KEY){
				$saveQuery[] = $this->saveString($fieldName, $this->$fieldName);	
			}
		}
		$query .= implode(", ", $saveQuery) . " WHERE `{$this->PRIVATE_KEY}` = " . $this->{$this->PRIVATE_KEY};
		return mysqli_query($con, $query);
	}
}


?>