简体   繁体   中英

PHP export to CSV - Doesnt Export newest Data

I have spent the past 5 or so hours searching forums and the internet for an answer to this issue.

Basically, I have a webpage where a table is generated using data collected from the Oracle SQL Server.

When the page loads, the table shows with the past 7 days worth of data. I have a date selection field with a "Go" button and an "Export to CSV" button.

If I click the Export button it prompts be to save or open. The CSV is fine it has the correct Data etc etc.

The issue is, when I select a date using the date selection field and hit go... the Table on the page refreshes showing me the data for the specific day. If I then click Export to CSV, the data seems to still be the original Data from when the page first loaded.

This is my code... I am sorry if the code isn't very great I am a complete novice to php.

if(isset($_POST['csv'])) $csv_request=$_POST['csv']; else $csv_request="";  
if(isset($_POST['datepicker'])) $date_filter=$_POST['datepicker']; else $date_filter="";

$output_csv = "";
$chosenDate = $date_filter;

if($chosenDate== "" || $chosenDate == Null){
        $mywhere = 'where timestamp >= trunc(sysdate)-7';
    }
    elseif ($chosenDate=='datepicker'){
            $date_chosen = $_POST['datePicker'];
            $mywhere = "where timestamp like to_date('$date_chosen', 'dd/mm/yyyy')";
    }


        $sql =  "Select to_char(timestamp, 'dd/mm/yy hh24:mi') timestamp, site, sum(Manual_coos) Manual_COOS,Sum(Faulty_COOS) Faulty_COOS, bearer from t_ca_Processed
                    ".$mywhere."
                    AND bearer = '4G'
                    AND faulty_coos = 1
                    group by timestamp, site, Manual_coos, Faulty_COOS, bearer
                UNION ALL
                Select to_char(timestamp, 'dd/mm/yy hh24:mi') timestamp, site, sum(Manual_coos) Manual_COOS,Sum(Faulty_COOS) Faulty_COOS, bearer from t_ca_Processed
                    ".$mywhere."
                    AND bearer = '4G'
                    AND Manual_coos = 1
                    group by timestamp, site, Manual_coos, Faulty_COOS, bearer
                Order by timestamp ASC";



            $st = $db->execute($sql);

        $output = "<table class = 'sortable' border = 1 Align = 'Center'>
                        <tr style = 'background-color: #f00;'>
                            <th>TimeStamp</th>
                            <th>Site</th>
                            <th>Manual COOS Total</th>
                            <th>Faulty COOS Total</th>
                            <th>Bearer</th>
                        </tr>";

        $output_csv = "TimeStamp,Site,Manual COOS Total,Faulty COOS Total,Bearer\n";
        $counter = 0;

        while (($row = oci_fetch_row($st)) != false)
            {
                    $output .= "<tr";

                    $output .= "><td>$row[0]</td>
                        <td align=center>$row[1]</td>
                        <td align=center>$row[2]</td>
                        <td align=center>$row[3]</td>
                        <td align=center>$row[4]</td></tr>\n";

                    $output_csv .= "$row[0],$row[1],$row[2],$row[3],$row[4]\n";
                    $counter ++;
            }
        $output .= "</table>";
        unset($db);

    If ($csv_request=='csv'){

        header("Content-Type: application/octet-stream");
        header("Content-Disposition: attachment; filename=\"".$File_name.".csv\";");
        header("Content-Transfer-Encoding: binary");
        echo $output_csv;
    }
    else
    {   

This is my HTML

 <!DOCTYPE html>
<html>
    <head>
    <style>
        table.sortable tbody tr:nth-child(2n) td {
        background: #DDDDDD;
        }
        table.sortable tbody tr:nth-child(2n+1) td {
        background: #ccfffff;
        }
    </style>
        <script type='text/javascript' src="/common/javascript/kpc_sorttable2.js"></script>
        <script type='text/javascript' src='/common/flot/jquery.js'></script>
        <script type="text/javascript" src="/common/jquery/ui/1.10.2/ui/jquery-ui.js"></script>
        <script type="text/javascript" src="/Common/jQuery/ui/1.10.2/ui/jquery.ui.core.js"></script>
        <script type="text/javascript" src="/Common/jQuery/ui/1.10.2/ui/jquery.ui.widget.js"></script>
        <script type="text/javascript" src="/Common/jQuery/ui/1.10.2/ui/jquery.ui.datepicker.js"></script>
        <link rel= 'stylesheet' type=text/css href='/common/style.css'>
        <script>
                $(function() {
                    $( "#datepicker" ).datepicker({
                        dateFormat: 'dd/mm/yy'
                    })
                })
        </script>
        <script>

        </script>
    </head>
    <body>

        <?php   generateHeader($menu,'4G Cells Down',1); ?>
        <div class='whitebox'>
        <form method='post' action="" name="parameters" id="parameters">
            <input type='hidden' name='csv' value='csv'>
            <input type='submit' value="Export as CSV" style="float: right;">
        </form>
        <form method='post' action="" name="parameters1" id="parameters1">
            <h3>Last Refreshed <?= $page_load_time ?></h3>
            <input type='hidden' name='datepicker' value='datepicker'>
            <h3>Date: <input type="text" id="datepicker" name="datePicker"><input type='submit' value="Go"></h3>
            <p><?= $output ?><p>
        </form>
        </div>
        <?php
            generateFooter();
        ?>
    </body>
</html> 
<?php } ?>

when I echo $output_csv I always see the newest data set... however the CSV is always the original Data. I have tried to Echo the CSV and I get an error saying headers have already been sent...

I am wondering if when the page originally loads, the csv has been created and only gets prompted to download once I hit the export button and when I have the new data, the file cannot be re-written?

Again sorry if im not very clear, new to this :)

cheers Mike

Your file probably gets cached by the webserver. If you add a Cache buster and/or cache header it should work.

header("Content-Transfer-Encoding: binary");
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

More info about the PHP header function, including caching directives.

If you generate a unique filename for each change or request, it will also be seen as a new file and caching will be disabled.

# Generate a unique name for each request
$File_name = uniqid($File_name . "_");
header("Content-Disposition: attachment; filename=\"".$File_name.".csv\";");

See PHP function uniqid for more specifics about the functionality.

The problem is that when you search for a date, the page refresh and the form refresh too, so when you click on the export csv the "request" is to get the default view. Keep your form (selected data) updated with the current view.

The value of this

<input type="text" id="datepicker" name="datePicker">

have to been keep always with the current view

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