【问题标题】:How to add a text at the end of each lines of downloaded file from mysql?如何在从mysql下载的每行文件的末尾添加一个文本?
【发布时间】: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,请花精力学习 PDOmysqli 数据库扩展。 Start here
  • 那么你如何决定要在这个新列中添加什么文本以及年龄
  • 最后你会看到我想要生成的 csv 示例。

标签: php mysql csv export-to-csv


【解决方案1】:

我自己找到了解决办法,分享给大家

我加了

echo "text_added;";

紧接着

for($i = 0; $i < $field; $i++) {$csv_export.= mysql_field_name($query,$i).';';}
$csv_export.= '\n';

改变了

for($i = 0; $i < $field; $i++) {
    $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
  } 
  $csv_export.= '
';  
}

        for($i = 0; $i < $field; $i++) { $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";'; }
$csv_export.= '
'.$row['age'].'years old";';
}

最后我得到了这个结果:

text_added;name;age;country
"21 years old"; "Gulizer"; "21"; "Kurdistan"
"20 years old"; "Pierre"; "20"; "France";

正是我想要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-05
    • 1970-01-01
    • 2012-07-03
    • 2014-05-29
    • 1970-01-01
    • 2023-02-07
    • 2016-12-23
    • 2018-06-15
    相关资源
    最近更新 更多