Reputation: 119
What I want to do is exporting an SQL query to a .csv file so that it can be downloaded by the user. The query is more or less like this:
SELECT * FROM {registered} WHERE pending = 'Y'
I want the result of that query to be put in a .csv file and I also want the rows in questions to be updated with pending = 'N' and completed_time = NOW().
I also want the headers to be included at the top.
Is there any standard drupal functions that should be used or should I simply use the file_create_filename function and then create the file the normal php way?
I tried doing like this:
// Save query data
$result = db_query("SELECT *
INTO OUTFILE '/tmp/myfile-raw'
FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
FROM {plan_tax_red_registered}");
if (!$result) {
echo 'Failed saving query\n';
return ;
}
$file = fopen("/tmp/myfile-raw","rw+");
if (!$file) {
echo 'Failed opening again\n';
return ;
}
// Might be uneccessary but database fields can change
$columns = db_query("SHOW FIELDS FROM {plan_tax_red_registered}");
$list_of_columns = array();
while ($res = db_fetch_array($columns)) {
$list_of_columns[] = $res['Field'];
}
$header = implode(";", $list_of_columns);
// Get the contents from the raw file
$old_content = file_get_contents($file);
// Save result
$csv_file = fopen("/tmp/result.csv","rw+");
if (!$csv_file) {
echo "Failed opening csv file\n";
return;
}
fwrite($csv_file, $header . "\n" . $old_content);
fclose($file);
fclose($csv_file);
Unfortunately, I couldn't open the csv file :(
I know I could simply do this to show the file:
function plan_tax_red_export_to_excel($result, $filename = 'myfile.csv'){
drupal_set_header('Content-Type: text/csv');
drupal_set_header('Content-Disposition: attachment; filename=' . $filename);
$count = mysql_num_fields($result);
for($i = 0; $i < $count; $i++){
$header[] = mysql_field_name($result, $i);
}
print implode(';', $header) ."\r\n";
while($row = db_fetch_array($result)){
foreach($row as $value){
$values[] = '"' . str_replace('"', '""', decode_entities(strip_tags($value))) . '"';
}
print implode(';', $values) ."\r\n";
unset($values);
}
}
But I want to update the content as well (setting the is_pending field to 'N' and completed_time to NOW()).
What are your ideas? Any help is appreciated :)
Kind regards, Samuel
Upvotes: 0
Views: 2694
Reputation: 5642
Have you considered using existing modules? You can create a CSV export using Views in combination with Views Bonus Pack or Views Data Export.
Upvotes: 1