简体   繁体   English

使用PHP POST从MYSQL下载CSV文件

[英]Download a CSV file from MYSQL with PHP POST

I am unable to create a script to download a CSV file. 我无法创建脚本来下载CSV文件。 every time I run the script it breaks. 每次我运行脚本时,它都会中断。 I am not receiving any errors. 我没有收到任何错误。 The page just stops loading once it gets to the script. 该页面进入脚本后即停止加载。 I have looked around and found some answers but none of them seem to be working. 我环顾四周,发现了一些答案,但似乎都没有用。 I am new to php, and would greatly appreciate an explanation if you know whats going on here. 我是php的新手,如果您知道这里发生了什么,将不胜感激。 Thanks in advance! 提前致谢!

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;
    }
   }
 }
}

Try 尝试

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

The comparison operator you are using is checking for 'not identical' and not 'not equal' 您正在使用的比较运算符正在检查“不相同”和“不相等”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM