<?

// relay the request to ian's website so we get the data there too.
// comment this next line out if you don't want to do this.
@file_get_contents( "http://ian-hawkins.com/torque.php?".$_SERVER['QUERY_STRING'] ) ;

// make the connection to the DB
$db_user = "torqueuser";
$db_pass = "torquepass";
$db_name = "torque";
$db_table = "raw_logs";
$link = mysql_connect('localhost', $db_user, $db_pass);
$db = mysql_select_db($db_name);

// now we've got the db connection, lets make sure the fields exist for all the data we're going to insert.
// get all the fields first
$result = mysql_query("SHOW COLUMNS FROM raw_logs");
if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        $dbfields[]=($row['Field']);
    }
}
// check through the k* _GET arguments to make sure there's a field to insert into
foreach ($_GET as $key => $value) {
	$keys[] = $key;
	if (preg_match("/^k/", $key)) {
		$values[] = $value;
	} else {
		$values[] = "'".$value."'";
	}
	if (!in_array($key, $dbfields)) {
		// if the field doesn't exist, alter the table to add it.
		mysql_query("ALTER TABLE $db_table ADD $key VARCHAR(255) NOT NULL default '0';");// || print mysql_error()."\n";
	}
}

// we've 2 arrays, the fields($keys) and the data($values) so throw them into the database.
$sql = "insert into $db_table (".join(",", $keys).") VALUES (".join(",", $values).")";
mysql_query($sql); 

// torque expects the page to return OK! so this should be the only output of this page in production.
print "OK!";
?>
