In my web site I'm creating a table from the mysql data and then now I want to add a export button buttom of the table so that a user will be able to download the data as an CSV file.
To do that I wrote dummy form:
<form action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<input type="submit" name="submit" value="Click Me">
</form>
And at the top of the php file I have:
if(isset($_POST['submit'])) {
export();
}
In my export function I have some mysql stuff, I'm creating an array and pushing data into it, and then:
$header = array('name', 'date', 'total', 'success', 'opens', 'clicks', 'success_rate', 'open_rate', 'CTO', 'CTR')
$fp = fopen('exportme2.csv', 'w');
fputcsv($fp, $header);
foreach ($data as $lines) {
fputcsv($fp, $lines);
}
fclose($fp);
After I click to export button, I'll have exportme2.csv file, however it is empty ! The data may be wrong so that there won't be anything but at least I should have the header names.
Can you help me about this issue please ?
Thanks.
First off, change
$fp = fopen('exportme2.csv', 'w');
to
$fp = fopen('exportme2.csv', 'a');
as 'w'
truncates the file, where 'a'
creates or appends the file.
Then you should use flock()
to make sure two different users (threads) don't try to write to the file at the same time:
if (!flock($fp, LOCK_EX)) {
error_log('Cannot get lock!');
} else {
fputcsv($fp, $header);
foreach ($data as $lines) {
fputcsv($fp, $lines);
}
}
If that doesn't fix things, then you have a typo in your code somewhere that isn't obvious to me.