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条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥20 大学计算机网络实验报告
      • ¥20 Oracle触发器,用户管理题目
      • ¥250 python的exchangelib 报错
      • ¥15 Oracle外部过程获取的句柄属性为空
      • ¥20 snmpv3相关提问
      • ¥20 boost电路升压频率和占空比选择
      • ¥15 找个人工智能的大佬咨询一些毕设问题
      • ¥15 需要教程:GD32F450I移植无系统lwip
      • ¥15 中文语料库检索构式 求助
      • ¥15 关于naver点击量信息