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

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

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目