Question

The problem with this code is that each time I export from MySQL to csv it overwrites the already created csv. I want this code to check if there is an already created csv file -> create new one. Ex. (Sales-2012-9-8.csv) to (Sales1-2012-9-8.csv)...This code works great on exporting records from MySQL..But when it comes to export another csv it overwrites the current csv file name.

Oh yea, one more thing..How is it possible to add Table Headers at the first row of csv file. Ex ( Item No - Qty - Selling Price - Date )?

Thank You

<?php
require_once('connect_db.php');
$fdate = $_POST['fdate'];
$tdate = $_POST['tdate'];

$result = mysql_query("SELECT item_no, qty, discount_price, date FROM sold_items WHERE date BETWEEN '".$fdate."' AND '".$tdate."' ORDER BY date Desc");

$filename = $name = "Sales";
$index = 1;
while(file_exists($filename)) {
  $filename = $name.$index;
  $index++;
  echo "File Already Exists";
}

if(!$f = fopen("E:/{$filename}-{$tdate}.csv", 'w')){
    ?>
    <script language="javascript">
    alert('USB FLASH NOT INSERTED');
    history.back();
    </script>
    <?php
}

while($row = mysql_fetch_array($result, MYSQL_NUM))
{
    fputcsv($f, $row);
}

fclose($f);


?>
<center><font style="font-size:28px; font-weight:bold; color:#C00;">USB Transfer Successful</font></center> 
<center><input type="button" onclick="javascript:window.close()" value="Close Window" /></center>
<?php

?>
Was it helpful?

Solution

Try this variant. I think file_exists() function see into other folder than "E:/":

$tdate = date();
$filename = $name = "Sales";
$index = 1;
while(file_exists("E:/{$filename}-{$tdate}.csv")) {
  $filename = $name.$index;
  $index++;
  echo "File {$filename}-{$tdate}.csv Already Exists";
}

if(!$f = fopen("E:/{$filename}-{$tdate}.csv", 'w')){
    ?>
    <script language="javascript">
    alert('USB FLASH NOT INSERTED');
    history.back();
    </script>
    <?php
}

As for the second question:

Oh yea, one more thing..How is it possible to add Table Headers at the first row of csv file. Ex ( Item No - Qty - Selling Price - Date )?

As I know, the first line of a csv-file is recognized as headers. So, try write your headers before writing the query results. E.g.

fputcsv($f, array('Item No', 'Qty', 'Selling Price', 'Date'));

OTHER TIPS

You're only checking the filename with the value "Sales" - The date isn't included yet!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top