【问题标题】:Download a CSV file from MYSQL with PHP POST使用 PHP POST 从 MYSQL 下载 CSV 文件
【发布时间】:2014-03-28 12:14:00
【问题描述】:

我无法创建脚本来下载 CSV 文件。每次我运行脚本时它都会中断。我没有收到任何错误。页面到达脚本后就会停止加载。我环顾四周,找到了一些答案,但似乎都没有奏效。我是 php 新手,如果你知道这里发生了什么,我将不胜感激。提前致谢!

if (isset($_POST['downloadCSV'])) {

$list = null;
include 'classes/Credentials.php';

try     
 {
 // Include globals from credentials.
 global $dbname, $host, $user, $pass;

// Set up on database switch
$conn = new PDO("mysql:dbname=$dbname;host=$host", $user, $pass);
$conn->exec("SET CHARACTER SET utf8");


        } catch(PDOException $e) {
            echo $e->getMessage();
                                }

 // Define and perform the SQL SELECT query
  $sql = 'SELECT * FROM rental';
  $result = $conn->query($sql);

 // If the SQL query is succesfully performed ($result not false)
  if($result !== false) 
  {
    $num_fields = mysql_num_fields($result);
    $headers = array();

    for ($i = 0; $i < $num_fields; $i++) {
    $headers[] = mysql_field_name($result , $i);             
    $fp = fopen('php://output', 'w');

    if ($fp && $result) {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="export.csv"');
        header('Pragma: no-cache');
        header('Expires: 0');
        fputcsv($fp, $headers);

        while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
        }

        $conn = null;        // Disconnect
        die;
    }
   }
 }
}

【问题讨论】:

  • 我没有收到错误消息。 CSV 文件只是不下载。我试过 echo $result;并且它不输出任何内容并且页面停止加载。我不确定错误在哪里。我不确定如何从这一点进行故障排除。一段时间以来一直在尝试解决这个问题。

标签: php mysql csv download


【解决方案1】:

试试

// If the SQL query is succesfully performed ($result not false)
if($result != false) {

您使用的比较运算符正在检查“不完全相同”而不是“不等于”

【讨论】:

    猜你喜欢
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 2018-01-02
    • 2015-12-12
    相关资源
    最近更新 更多