duanqiongchong0354 2018-10-05 16:23
浏览 83
已采纳

使用PHP从远程MySQL创建CSV文件

I have adapted the info from this site but instead of creating a csv file, it is only displaying the info in the command screen it is being executed in. I have tried entering $fileName = 'C:\Users\dmcgettigan\Desktop\mysql-export.csv'; and just the filename but I do not have a file being generated. Thank you in advance for your help, I am trying to teach myself php, and mysql!

Updated: added code

My Code:

<?php

//Our MySQL connection details.
$host = 'mysql_server';
$user = 'user';
$password = 'password';
$database = 'database';

//Connect to MySQL using PDO.
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);

//Create our SQL query.
$sql = "SELECT 
    a.InvoiceNumber, a.partnumber, a.Quantity, b.Discount, date
FROM
    data a,
    mars b
WHERE
    a.PartNumber = b.partnumber
        AND date >= '2018-09-28'
        AND mfg = 'gk'
        AND discount <> '0.00'
        AND CustomerNumber IN ('Z5447520' , 'Z3715177', 'Z1234444', 'Z5425966')
        AND Quantity > '0'";

//Prepare our SQL query.
$statement = $pdo->prepare($sql);

//Executre our SQL query.
$statement->execute();

//Fetch all of the rows from our MySQL table.
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);

//Get the column names.
$columnNames = array();
if(!empty($rows)){
    //We only need to loop through the first row of our result
    //in order to collate the column names.
    $firstRow = $rows[0];
    foreach($firstRow as $colName => $val){
        $columnNames[] = $colName;
    }
}

//Setup the filename that our CSV will have when it is downloaded.
$fileName = 'mysql-export.csv';

//Set the Content-Type and Content-Disposition headers to force the download.
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="' . $fileName . '"');

//Open up a file pointer
$fp = fopen('php://output', 'w');

//Start off by writing the column names to the file.
fputcsv($fp, $columnNames);

//Then, loop through the rows and write them to the CSV file.
foreach ($rows as $row) {
    fputcsv($fp, $row);
}

//Close the file pointer.
fclose($fp);
  • 写回答

1条回答 默认 最新

  • duana1986 2018-10-05 19:18
    关注

    $fp = fopen('php://output', 'w'); this specific line should be changed to $fp = fopen($filename, 'w'); because as is you are using the output as the file

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程