My code export a .csv file, depending on sql code. I inserted 3 variables start_month
, finish_month
and year
to export the data to a specific time.
I do not know how to do that by pressing the button csv export to export .csv file depending on the entered values in the three variables.
<?php
// call export function
exportMysqlToCsv('export.csv');
// export csv
function exportMysqlToCsv($filename = 'export.csv')
{
$conn = dbConnection();
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//var for period
$start_month = trim($_POST['start_month']);
$finish_month = trim($_POST['finish_month']);
$year = trim($_POST['year']);
$sql_query = "SELECT
activitati.tip,
clienti.NUME_J,
clienti.NUME_F,
activitati.month,
activitati.year
FROM activitati
JOIN clienti ON clienti.ID = activitati.ID_CLIENT
JOIN dotari ON activitati.ID_DOTARE = dotari.ID
WHERE liamed.activitati.TIP = "Delivery"
AND activitati.month BETWEEN "{$start_month}" AND "{$finish_month}"
AND activitati.year_DATA_ACTIVITATE = "{$year}"
LIMIT 50;";
//execute this sql and fetch your results as needed
// Gets the data from the database
$result = $conn->query($sql_query);
$f = fopen('php://temp', 'wt');
$first = true;
while ($row = $result->fetch_assoc()) {
if ($first) {
fputcsv($f, array_keys($row), ';');
$first = false;
}
fputcsv($f, $row, ';');
} // end while
$conn->close();
$size = ftell($f);
rewind($f);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: $size");
// Output to browser with appropriate mime type, you choose ;)
header("Content-type: text/x-csv");
header("Content-type: text/csv");
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename");
fpassthru($f);
exit;
}
// db connection function
function dbConnection(){
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "delivery";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
?>
<form>
Insert start month:<input type="text" name="start_month" ><br>
Insert finish month: <input type="text" name="finish_month" ><br>
Insert year:<input type="text" name="year"><br>
<input type="submit" name="button" value="export csv">
</form>
Thank you!
</div>