【发布时间】:2017-04-19 18:19:39
【问题描述】:
这是我运行良好的代码。当我从浏览器调用此文件时,它会以 CSV 格式下载我的文件。
<?php
/* vars for export */
// database record to be exported
$db_record = 'people';
// optional where query
$where = 'WHERE 1 ORDER BY 1';
// filename for export
$csv_filename = 'exported.csv';
// database variables
$hostname = "localhost";
$user = "root";
$password = "";
$database = "db1";
// Database connecten voor alle services
mysql_connect($hostname, $user, $password)
or die('Could not connect: ' . mysql_error());
mysql_select_db($database)
or die ('Could not select database ' . mysql_error());
// create empty variable to be filled with export data
$csv_export = '';
// query to get data from database
$query = mysql_query("SELECT * FROM ".$db_record." ".$where);
$field = mysql_num_fields($query);
// create line with field names
for($i = 0; $i < $field; $i++) {
$csv_export.= mysql_field_name($query,$i).';';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysql_fetch_array($query)) {
// create line with field values
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
}
$csv_export.= '
';
}
// Export the data and prompt a csv file for download
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
echo($csv_export);
?>
假设生成的文件是这样的:
"name", "age", "country"
"Gulizer", "21", "Kurdistan"
"Pierre", "20", "France"
我想要的是再次检索年龄并将其放在每一行的和中,并带有一些文本,例如
"name", "age", "country", "text_added"
"Gulizer", "21", "Kurdistan", "The age of Gulizer is 21"
有可能吗?
【问题讨论】:
-
SELECT INTO OUTFILE 有什么问题?
-
没什么。效果很好
-
每次在新代码中使用the
mysql_数据库扩展a Kitten is strangled somewhere in the world 时,它都已被弃用,并且已经存在多年,并且在 PHP7 中永远消失了。如果您只是学习 PHP,请花精力学习PDO或mysqli数据库扩展。 Start here -
那么你如何决定要在这个新列中添加什么文本以及年龄
-
最后你会看到我想要生成的 csv 示例。
标签: php mysql csv export-to-csv