duanqiongchong0354 2018-10-05 16:23
浏览 83


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:


//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
    data a,
    mars b
    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.

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

//Get the column names.
$columnNames = array();
    //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.
  • 写回答

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

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



  • ¥21 matlab怎么求时域信号的二阶导数
  • ¥15 判断两个表是否完全相同
  • ¥15 java map类型数据格式,如何快速通过前缀匹配元素
  • ¥15 stc12c5a60s2、QMC5883L、LCD1602组合测量磁场所需程序
  • ¥15 vba参数转c++ SAFEARRAY
  • ¥20 Win11测试yolov4,“找不到nvcuda.dll”怎么办?
  • ¥15 simulink绘制bode图
  • ¥15 php_network_getaddresses: getaddrinfo failed: Name or service not known
  • ¥15 用msg发消息出现的问题
  • ¥15 unity3d机械臂