PHP:插入句点并导出.csv

时间:2016-02-10 06:09:30

标签: php csv

我的代码导出.csv文件,具体取决于sql代码。我插入了3个变量start_monthfinish_monthyear,以将数据导出到特定时间。 我不知道如何按 csv export 按钮导出.csv文件,具体取决于三个变量中输入的值。

<?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>

谢谢!

1 个答案:

答案 0 :(得分:1)

您需要更改WHERE子句以使用monthyear数据库列:

此:

AND activitati.LUNA_DATA_ACTIVITATE BETWEEN "{$start_month}" AND "{$finish_month}"
AND activitati.ANUL_DATA_ACTIVITATE = "{$year}"

变为:

AND activitati.month BETWEEN "{$start_month}" AND "{$finish_month}"
AND activitati.year = "{$year}"

不要忘记清理表单输入,你不想要SQL vulnerability

Hint, hint...

相关问题