【问题标题】:Changing database values for CSV export更改 CSV 导出的数据库值
【发布时间】:2011-12-01 14:57:24
【问题描述】:

我有一个 CSV 导出脚本,它从某个表中获取某些字段及其值,并使用数据创建一个 Excel 文件。请参阅下面的脚本。

它首先获取列名(ID 除外)。 其次,它将获取 firstname、lastname、employee_id、unit 和 present 的值,并将所有这些值放入 Excel 文件中。

现在注意它从表中抓取数据:table_info 在此表中,UNIT 和 PRESENT 仅存在于数字之外。这些数字代表其他两个表格中的单位/礼物的 ID:

table_units (id, 标题) table_presents (id, title)

我想要的是,在 Excel 工作表中,它不显示单元/礼物的数字(id),而是显示单元/礼物的标题。我怎样才能做到这一点?我的 PHP 知识就到此为止了。

        $table = 'table_info';
    $file = 'export';

    $result = mysql_query("SHOW COLUMNS FROM ".$table."");
    $i = 0;
    if (mysql_num_rows($result) > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            if($row['Field'] != 'id'){
                $csv_output .= $row['Field']."; ";
                $i++;
            }
        }
    }
    $csv_output .= "\n";

    $values = mysql_query("SELECT firstname, familyname, employee_id, unit, present FROM ".$table."") or die(mysql_error());
    while ($rowr = mysql_fetch_row($values)) {

        for ($j=0;$j<$i;$j++) { 
            $csv_output .= $rowr[$j]."; ";
        }
        $csv_output .= "\n";
    }

    $filename = $file."_".date("Y-m-d_H-i",time());
    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: csv" . date("Y-m-d") . ".csv");
    header("Content-disposition: filename=".$filename.".csv");
    print $csv_output;
    exit;

【问题讨论】:

    标签: php mysql export-to-csv


    【解决方案1】:

    更改您的 sql 查询以执行包含 table_units 和 table_presents 的连接。或者,如果您担心连接会导致性能瓶颈,您可以将 table_units 和 table_presents 存储在以 ID 为键的数组中,当您拥有外键(unit_id、present_id)时可以引用它们。

    【讨论】:

      【解决方案2】:

      不知道你为什么使用; 而不是,

      这是我发现的问题:-

      $result = mysql_query("SHOW COLUMNS FROM ".$table."");
      ==>
      $result = mysql_query("SHOW COLUMNS FROM ".$table." WHERE Field!='id'");
      // so, it would skip column id
      

      所有的for ($i ... ) 都是不必要的,而且每一行都有额外的;
      改为内爆:-

      $csv_output .= $row['Field']."; ";
      ==>
      $csv_output .= implode(';', $row);
      

      【讨论】:

        猜你喜欢
        • 2015-03-24
        • 1970-01-01
        • 2022-11-21
        • 1970-01-01
        • 1970-01-01
        • 2013-06-17
        • 1970-01-01
        • 1970-01-01
        • 2016-11-07
        相关资源
        最近更新 更多