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

标签 php mysql csv export

我已经改编了此信息 site但它不是创建 csv 文件,而是仅在正在执行的命令屏幕中显示信息。我尝试输入 $fileName = 'C:\Users\dmcgettigan\Desktop\mysql-export.csv' ; 只是文件名,但我没有生成文件。预先感谢您的帮助,我正在尝试自学 php 和 mysql!

更新:添加代码

我的代码:

<?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);

最佳答案

$fp = fopen('php://output', 'w'); 此特定行应更改为 $fp = fopen($filename, 'w') ; 因为您正在使用输出作为文件

关于php - 使用 PHP 从远程 MySQL 创建 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52669772/

相关文章:

仅使用一个扫描仪的 java.util.NoSuchElementException

java - 如何使用 logback 以 csv 格式写入日志文件?

php - 动态更改时间戳 - 建议?

php - 使用 PHP 检测日历事件重叠冲突

php - 从数据库中搜索字符串并获取接近单词的 php

mysql - 根据mysql的另一个表(4个表)值更新表

php - CakePHP 分页导致奇怪的 DISTINCT 行为

MySQL 子查询将查询连接到现有查询

postgresql - 从 CSV 文件更新 PostgreSQL 表

PHP 7.1 用动态变量替换多个值