WPDB将自定义查询导出到csv - 未创建文件

时间:2018-04-08 04:41:19

标签: database wordpress

我正在使用以下代码将自定义MYSQL查询导出为CSV。数据和列标题工作正常(打印$ csv_output;完全符合我的预期)但是没有创建实际的CSV文件。

我出错了什么?

function generate_csv(){

    global $wpdb;
    $table_name = $wpdb->prefix."ck_shipment";// table name
    $file = 'database_csv'; // csv file name
    $results = $wpdb->get_results("SELECT * FROM $table_name",ARRAY_A );

    // get column names
    $query = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`='".$wpdb->dbname."' AND `TABLE_NAME`='".$table_name."'";
    $columnNamesList = $wpdb->get_results($query);  

    foreach ( $columnNamesList as $column_name ) {
        $csv_output.=$column_name->COLUMN_NAME.",";
    }

    // remove last additional comma 
    $csv_output = substr($csv_output,0,strlen($csv_output)-1);

    // start dumping csv rows in new line
    $csv_output.="\n";

    if(count($results) > 0){
      foreach($results as $result){
      $result = array_values($result);
      $result = implode(", ", $result);
      $csv_output .= $result."\n";
        }
      }

    $filename = $file."_".date("Y-m-d_H-i",time());
    print $csv_output;
    exit;
}


?>
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<br /><input type="submit" name="export" value="export" class="button-primary"> 
</form>
<?php

if (isset($_POST['export'])) {
    generate_csv();
}   

谢谢!

0 个答案:

没有答案