I want to export a sql query. I've tried the code below. I don't get any errors, but the output file is blank.
function ff_export2csv($sql, $del)
// This function takes an SQL query and the field delimiter
// to send the result of the query to a file on the client's computer
{
global $database, $file, $ff_compath, $ff_version, $mosConfig_fileperms;
// set the filename to a kind of unique
// in the exports directory under com_facileforms
$filename = $ff_compath.'/exports/export-'.date('YmdHis').'.csv';
$existed = file_exists($filename); // test the file
if ($existed) {
$permission = is_writable($filename);
if (!$permission) {
echo "<script> alert('Exportfile not writeable!'); window.history.go(-1);</script>\n";
exit();
} // if
} // if
$file=fopen($filename, "w");
$database->setQuery($sql);
$rows = $database->loadObjectList();
if ($database->getErrorNum()) {
echo $database->stderr();
return false;
} // if
if (!count($rows)) echo "<script> alert('No records found to export!');</script>\n";
if (!($del)) $del=", "; // set delimiter to a default value if not set...
$data=""; // var to hold the processed results
// lines in the csv file
foreach ($rows as $row) {
// only the first field does not get a delimiter
$writeDelimiter = FALSE;
// fields in the csv file
foreach ($row as $field) {
// Replaces a double quote with two double quotes
$field=str_replace("\"", "\"\"", $field);
// Adds a delimiter before each field (except the first)
if($writeDelimiter) $data .= $del;
$data .= $field;
$writeDelimiter = TRUE;
} // foreach
// add a newline to every line
$data .= "\r\n";
} // foreach
fwrite($file, $data);
fclose($file);
if (!$existed) {
$filemode = NULL;
if (isset($mosConfig_fileperms)) {
if ($mosConfig_fileperms!='') $filemode = octdec($mosConfig_fileperms);
} else $filemode = 0644;
if (isset($filemode)) @chmod($filename, $filemode);
} // if
return $filename;
} // end function
function ff_download($path) {
session_write_close();
ob_end_clean();
if (!is_file($path) || connection_status()!=0)
return(FALSE);
//to prevent long file from getting cut off from //max_execution_time
set_time_limit(0);
$name=basename($path);
//filenames in IE containing dots will screw up the
//filename unless we add this
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE"))
$name = preg_replace('/\./', '%2e', $name, substr_count($name, '.') - 1);
//required, or it might try to send the serving //document instead of the file
header("Cache-Control: ");
header("Pragma: ");
header("Content-Type: application/octet-stream");
header("Content-Length: " .(string)(filesize($path)) );
header('Content-Disposition: attachment; filename="'.$name.'"');
header("Content-Transfer-Encoding: binary\n");
if($file = fopen($path, 'rb')){
while( (!feof($file)) && (connection_status()==0) ){
print(fread($file, 1024*8));
flush();
}
fclose($file);
}
return((connection_status()==0) and !connection_aborted());
}