<?

/*/
	© 2002-2004 by Locke Enterprises (www.iLocke.com) - All rights reserved.
	LICENSE: Authorized for single-copy use on the AutoGlassHosting.com website. Any other use is expressly prohibited.
	FILE:  db.phi [v2.1]
	PURPOSE:  Export $hDB - a link to this site's main mysql database.
	CREATED:  Nathan - 7/31/2001
	MODIFICATION HISTORY:
		· 3/6/2002 - Nathan - added an optional defaultValue parameter to getField() so that errors can be easier detected by the caller
		· 6/18/2004 - Nathan - adapted for the AGH website / main db
		· mm/dd/yyyy - [name] - [comment]
/*/

/*/
	DATA:
		main:  mysqldump -u windshi_winddb --quote-names --password=parker --opt windshi_main > windshi_main.sql
		invoice:  mysqldump -u windshi_winddb --quote-names --password=parker --opt windshi_invoice > windshi_invoice.sql
	STRUCTURE:
		mysqldump -u windshi_winddb --quote-names --password=parker --opt --no-data windshi_main > windshi_main.sql
	IMPORT:
		main:  mysql -u windshi_winddb --password=parker windshi_main < windshi_main.sql
		invoice:  mysql -u windshi_winddb --password=parker windshi_invoice < windshi_invoice.sql
/*/


	$hDB = mysql_connect("localhost","windshi_winddb","parker") or die("Unable to connect to SQL server!");
	//$hDB = mysql_connect("67.19.14.122","windshi_winddb","parker") or die("Unable to connect to SQL server!");

	/// select the desired database...
	if( isset($_SESSION['CurrentDB']) && $_SESSION['CurrentDB'] != "" ) {
		mysql_select_db($_SESSION['CurrentDB']) or die( "Unable to select database: ".$_SESSION['CurrentDB']);
	} else {
		mysql_select_db("windshi_main") or die( "Unable to select the database!");
	}
	

//-------------------------------------------------------------------------
// getField:  Return the value of the specified field from the requested query -- or a specified default.
//-------------------------------------------------------------------------
function getField( $field, $SQL="", $defaultValue = "!{:NONE:}" ) {

	/// reasonable default is to get first field...
	if( $SQL=="" ) {
		$SQL = $field;
		$field = 0;
	}

	/// attempt the query...
	if( !($hData = mysql_query($SQL)) ) {
		if( $defaultValue == "!{:NONE:}" ) {
			return "ERROR: getField(1)<br>\n";
		} else {
			return $defaultValue;
		}
	}
	
	/// determine the value retrieved...
	//$value = ($data = mysql_fetch_array($hData)) ? $data[$field] : "ERROR: getField(2)<br>\n";
	if( $data = mysql_fetch_array($hData) ) {
		$value = $data[$field];
	} else {
		if( $defaultValue == "!{:NONE:}" ) {
			$value = "ERROR: getField(2)<br>\n";
		} else {
			$value = $defaultValue;
		}
	}

	/// cleanup...
	mysql_free_result($hData);
	return $value;
	
} // getField()


//-------------------------------------------------------------------------
// GetFields:  Return the values of the specified fields from the requested query -- or a specified default.
// Parameters: fieldsDelim = list of tilde~delimited fields to return from the query result array
//-------------------------------------------------------------------------
function GetFields( $fieldsDelim, $SQL="", $defaultArray=null ) {

	/// code for a smart function prototype with just the SQL string...
	if( $SQL == "" ) {
		$SQL = $fieldsDelim;
		$fieldsDelim = "";
	}
	
	/// attempt the query...
	if( !($hData = mysql_query( $SQL )) ) {
		if( $defaultArray==null ) {
			return array("ERROR: GetFields(1) - Bad query.<br>\n");
		} else {
			return $defaultArray;
		}
	}
	if( mysql_num_rows($hData)<1 ) {
		if( $defaultArray==null ) {
			return array("ERROR: GetFields(2) - No data values returned.<br>\n");
		} else {
			return $defaultArray;
		}
	}

	/// get the data (method depends upon needed results); return default values when none found...
	if( $fieldsDelim!="" ) {
		$query = ($rData = mysql_fetch_array($hData,MYSQL_ASSOC));
	} else {
		$query = ($rData = mysql_fetch_array($hData,MYSQL_NUM));
	}
	if( !$query ) {
		if( $defaultArray == null ) {
			return array("ERROR: GetFields(3) - Fetch error.<br>\n");
		} else {
			return $defaultArray;
		}
	}

	/// amass and return the requested field values...
	if( $fieldsDelim != "" ) {
		$fields = split( "~", $fieldsDelim );
		$returnArray = array();
		foreach( $fields as $field ) {
			$returnArray[] = $rData[$field];
		}
	} else {  // just smartly return the whole first row of data...
		foreach( $rData as $value ) {
			$returnArray[] = $value;
		}
	}
	return $returnArray;

} // GetFields()


//-------------------------------------------------------------------------
// getRow:  Return the first (only!) row array of the query specified.
//-------------------------------------------------------------------------
function getRow( $SQL, $defaultValue="!{:NONE:}" ) {

	/// attempt the query...
	if( !($hData = mysql_query( $SQL )) ) {
		if( $defaultValue == "!{:NONE:}" ) {
			return array("ERROR: getRow(1)<br>\n");
		} else {
			return array($defaultValue);
		}
	}
	
	/// return the row as an array...
	if( !($rData = mysql_fetch_array($hData)) ) {
		return array("ERROR: getRow(2)<br>\n");
	}
	mysql_free_result($hData);
	return $rData;
	
} // getRow()


//-------------------------------------------------------------------------
// getColumn:  Return an array of the requested field/column values from the query specified. Defaults to column index 0.
//-------------------------------------------------------------------------
function getColumn( $field, $SQL="", $defaultValue=null ) {

	/// smart single-parameter prototyping...
	if( $SQL=="" ) {
		$SQL = $field;
		$field = 0;
	}

	/// attempt the query...
	if( !($hData = mysql_query( $SQL )) ) {
		if( $defaultValue == null ) {
			return array("ERROR: getColumn(1)<br>\n");
		} else {
			return array($defaultValue);
		}
	}
	
	/// return the column as an array...
	$columnArray = array();
	while( !($rData = mysql_fetch_array($hData)) ) {
		$columnArray[] = $rData[$field];
	}
	mysql_free_result($hData);
	return $columnArray;
	
} // getColumn()


//-------------------------------------------------------------------------
// getCount:  Return the count of rows matching the specified criteria.
//-------------------------------------------------------------------------
function getCount( $table, $where="" ) {

	$where = isset($where) && $where!="" ? "WHERE $where" : "";
	if( !($hData = mysql_query("SELECT Count(*) FROM $table $where")) ) return "ERROR: getCount(1)<br>\n";
	$theCount = ($data = mysql_fetch_array($hData)) ? $data["Count(*)"] : "ERROR: getCount(2)<br>\n";
	mysql_free_result($hData);

	return $theCount;
	
} // getCount()


//-------------------------------------------------------------------------
// dbExecute:  Execute the statement on the database.
// 	Note: If the source file/routine is set, it is assumed that error reporting is on.
//-------------------------------------------------------------------------
function dbExecute( $sql, $source="" ) {

	global $PHP_SELF;
	
	/// run the command...
	if( mysql_query($sql) ) return true;

	/// there was an error...
	LogError($sql);
	if( isset($source)  &&  $source != "" ) {
		echo "<br><b><font color=#C00000>dbExecute ERROR:</font></b> (".$PHP_SELF." / ".$source.") ".mysql_errno()." - ".mysql_error()."<br>\n<!--\n:\n".$sql."\n:\n-->\n";
	}
	return false;

} // dbExecute()


//------------------------------------------------------------------------
// GetLastInsertID:  A shortcut to get the last inserted id.
//-------------------------------------------------------------------------
function GetLastInsertID( $table="" ) {
	
	if( $table ) {
		return intval( getField(0,"SELECT Last_Insert_ID() FROM $table LIMIT 1") );
	} else {
		return intval( getField(0,"SELECT Last_Insert_ID()") );
	}

} // GetLastInsertID()


//-------------------------------------------------------------------------
// sqlQuote:  Replaces ticks with double-ticks in preparation to use a string in an SQL command.
// Notes:
// 	Intended for use as in: list($a,$b,$c) = sqlQuote($q1,$q2,$q3); [- OR -] $a = sqlQuote($a1)
//		Also flattens out any arrays passed into the array sent, and can also be used as: $arr2 = sqlQuote($arr1);
//-------------------------------------------------------------------------
function sqlQuote( $theString ) {

	return str_replace( "'", "''", $theString );

	/**//// disabled
    $quoted = array();
    $numargs = func_num_args();
    $temp = func_get_arg(0);
    if( $numargs==1 ) return str_replace("'","''",$temp);
    for( $i = 0; $i < $numargs; $i++ ) {
    	$temp = func_get_arg($i);
    	if( is_array($temp) ) {
    		for( $j = 0; $j < count($temp); $j++ ) {
    			$quoted[] = str_replace( "'", "''", $temp[$j] );
    		}
    	} else {
    		$quoted[] = str_replace( "'", "''", $temp );
    	}
    }
    return $quoted;

} // sqlQuote()


//-------------------------------------------------------------------------
// LogError:  Save the specified error into the 
//-------------------------------------------------------------------------
function LogError( $msg, $filename="", $routine="", $type="mysql" ) {

	global $PHP_SELF;
	
	//echo "<br>TEST<br><br>";
	if( $type=="mysql" ) {
		$sql = "INSERT INTO err SET script='".sqlQuote($PHP_SELF)."', file='".sqlQuote($filename)."', routine='".sqlQuote($routine)."', err='".sqlQuote(mysql_errno().": ".mysql_error())."\n<br>FROM SQL:\n<br>\n".sqlQuote($msg)."'";
	} else {
		$sql = "INSERT INTO err SET script='".sqlQuote($PHP_SELF)."', file='".sqlQuote($filename)."', routine='".sqlQuote($routine)."', err='".sqlQuote($msg)."'";
	}
	if( !mysql_query($sql) ) {
		echo "LogError() ERROR:<br><br>\n\n" . mysql_errno() . ": " . mysql_error()."\n\n<!--\n$sql\n-->\n";  // double-safe error reporting...
	}

} // LogError()


//-------------------------------------------------------------------------
// getArrayFromData:  Returns an array of all of the rows of data.
//-------------------------------------------------------------------------
function getArrayFromData( $hData ) {

	$theArray = array();
	while( $rData = mysql_fetch_array($hData) ) {
		$theArray[] = $rData;
	}
	return $theArray;
	
} // getArrayFromData()


//-------------------------------------------------------------------------
// getArrayFromQuery:  Returns an array of all of the rows of data from the specified query.
//-------------------------------------------------------------------------
function getArrayFromQuery( $SQL ) {

	return getArrayFromData(mysql_query($SQL));
	
} // getArrayFromQuery()


?>