2014-02-25 54 views
0

我無法創建腳本來下載CSV文件。每次我運行它的腳本都會中斷。我沒有收到任何錯誤。該頁面一旦到達腳本就停止加載。我環顧四周,發現一些答案,但他們似乎都沒有工作。我對PHP很陌生,如果你知道這裏發生了什麼,我將非常感謝你的解釋。提前致謝!使用PHP POST從MYSQL下載CSV文件

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

什麼錯誤? –

+0

我沒有收到錯誤消息。 CSV文件只是不下載。我已經嘗試echo $ result;並且它不輸出任何內容並且頁面停止加載。我不確定錯誤在哪裏。我不確定如何解決這一問題。一直試圖弄清楚這一點現在。 –

回答

0

嘗試

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

您正在使用的檢查比較運營商「不相同」,而不是「不等於」