我想问一下,在将php数据导出到csv之前是否可能先查询或过滤(例如:搜索名称)?我有一个代码将PHP数据导出到csv但我希望它首先被过滤。
这是我将php数据导出到csv的代码。
<?php
// call export function
exportMysqlToCsv('export_csv.csv');
// export csv
function exportMysqlToCsv($filename = 'export_csv.csv')
{
$conn = dbConnection();
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql_query = "SELECT id, name, code FROM toy";
// 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 = "louchin";
$dbname = "phppot_examples";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
return $conn;
}
?>
请尽可能帮助我并提出建议。谢谢!
答案 0 :(得分:0)
在SQL查询中调用数据:
$sql_query = "SELECT id, name, code FROM toy";
我认为您只需在此添加WHERE
子句即可添加过滤器。
快速推出谷歌版本的MySQL&#39;会给你很多地方,你可以查找语法。