<?PHP

if($_FILES["file"]["type"] != "application/vnd.ms-excel"){
?> 
  <script type="text/javascript"> 
    alert("This is not a CSV file."); 
    history.back(); 
  </script> 
<?php 
	

}
elseif(is_uploaded_file($_FILES['file']['tmp_name'])){
	//Connect to the database
	$dbhost = 'localhost';
	$dbuser = 'root';
	$dbpass = 'pulsar99';
	$dbname = 'test';
	$link = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql server');
	mysql_select_db($dbname);
	
	//Process the CSV file
	$iter = 0;
	$havg = 0;
	$att10 = 0;
	$handle = fopen($_FILES['file']['tmp_name'], "r");
	$data = fgetcsv($handle, 1000, ","); //Remove if CSV file does not have column headings
	while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
		$att0 = mysql_real_escape_string($data[0]);
		$att1 = mysql_real_escape_string($data[1]);
		$att2 = mysql_real_escape_string($data[2]);
		$att3 = mysql_real_escape_string($data[3]);
		$att4 = mysql_real_escape_string($data[4]);
		$att5 = mysql_real_escape_string($data[5]);
		$att6 = mysql_real_escape_string($data[6]);
		$att7 = mysql_real_escape_string($data[7]);
		$att8 = mysql_real_escape_string($data[8]);
		$att9 = mysql_real_escape_string($data[9]);
		
		$token = strtok($att1, "T");
		
		if($iter == "0")
		{
			$var1 = 'calE';
		}
		else 
		{
			$var1 = 'exec';
			$att10 = $att10 + $att6;			
		}

		$sql = "INSERT INTO decvalues (symbol, date, hrate) VALUES ('" . $var1 . "', '" . $token . "', '" . $att6 . "')";
		mysql_query($sql);		
		$iter++;
	}
	$var1 = 'avgE';
	$havg = $att10/$iter;
	$sql = "INSERT INTO decvalues (symbol, date, hrate) VALUES ('" . $var1 . "', '" . $token . "', '" . $havg . "')";
	mysql_query($sql);
	mysql_close($link);

	?> 
  	<script type="text/javascript"> 
    	alert("CSV file successfully imported."); 
    	history.back(); 
  	</script> 
	<?php 
}
else{
	die("You shouldn't be here");
}
?>
