简体   繁体   中英

PHP checking if csv file exists?

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

?>

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. Eg

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

您只需要检查文件名中“ Sales”的值-日期尚未包括!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM