Export data to .csv file using php

I have a database that collects data for researchers and I need to allow them to download the data they want easily into a .csv file. Here is my code that will use the select … into outfile … command.

//Grab Air Temperature Data if($colname_Data2 == 100) { mysql_select_db($database_ODM, $ODM); sprintf("SELECT DataValue, LocalDateTime, VariableID INTO OUTFILE '/tmp/Bing.csv' FIELDS TERMINATED BY ';' LINES TERMINATED BY '/n' FROM DataValues WHERE SiteID = %s AND (VariableID = 12 OR VariableID = 11 OR VariableID = 13) AND LocalDateTime >= DATE_ADD(NOW(), INTERVAL %s);", GetSQLValueString($colname_Data1, "int"), $QueryLimit); }

I can not figure out why the file is not created. Bing.csv is a place holder and I will eventually let them name the file they want. Bing.csv does not exist on the server so there is not failure from multiple files. If I do this while logged into MYSQL the file is created and I can look at it. Please help???

if you don’t mind the output being an xls file here’s a bit of code that will do the trick:

[php]function cleanData($str){
$str = preg_replace("/\t/", “\t”, $str);
$str = preg_replace("/\n/", “\n”, $str);
}

$filename = "list_data_" . date('Y-m-d-h-i-s') . ".xls"; 
header("Content-Disposition: attachment; filename=\"$filename\""); 
header("Content-Type: application/vnd.ms-excel"); 

$flag = false;  
$result = mysql_query("SELECT * FROM DataValues ") or die(mysql_error()); 
while(false !== ($row = mysql_fetch_assoc($result))) { 
 
	if(!$flag) { 
	# display field/column names as first row 
	echo implode("\t", array_keys($row)) . "\n"; 
	$flag = true; 
	} 
	array_walk($row, 'cleanData');
	echo implode("\t", array_values($row)) . "\n";
	}
}[/php]
Sponsor our Newsletter | Privacy Policy | Terms of Service