2017-07-30 67 views
0

iam新的PHP,我知道如何將靜態列的MySQL結果導出到CSV,但在某些情況下,我將不得不動態導出而不指定列名稱。我已經在下面試過了,我需要幫助才能完成這項工作。php導出mysql數據與動態列csv

PHP

<?php 
if(isset($_POST['action']) && $_POST['action'] == 'test_export_to_csv'){ 


$head_qry = mysql_query("SELECT `header_display_name` FROM expense_heading WHERE expense_id='$expense_id' order by col_order"); 

$columnValues = Array(); 

while ($row = mysql_fetch_assoc($head_qry)) { 

    $columnValues[] = $row['columnname']; 

} 
$filename = "uploads/reports/".$invoice_id.".csv"; 
$file = fopen($filename, 'w+'); 

fputcsv($file,$columnValues); 

$data_qry="SELECT $columnValues from invoice_detail where invoice_id='$invoice_id'"; 

$data_result=mysql_query($data_qry); 
while($result=mysql_fetch_assoc($data_result)){ 
    $report_array=array($result[$columnValues]); 
    fputcsv($file, $report_array); 
} 
fclose($file); 

if(ini_get('zlib.output_compression')) 
ini_set('zlib.output_compression', 'Off'); 


header("Pragma: public"); // required 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype"); 

// change, added quotes to allow spaces in filenames 
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";"); 
header("Content-Transfer-Encoding: binary"); 
header("Content-Length: ".filesize($filename)); 
readfile("$filename"); 
exit(); 
} 
+2

1 **不要**使用**過時和不安全的**'mysql_ *' -功能。從PHP 5.5(2013年)開始,它們已被棄用,並且在PHP 7中(2015年)完全刪除。改用MySQLi或PDO。 2. **您可以使用[SQL Injections](http://php.net/manual/en/security.database.sql-injection.php)**,並且確實應該使用[Prepared Statements](http:// php.net/manual/en/mysqli.quickstart.prepared-statements.php),而不是串聯你的查詢,如果你使用上面提到的MySQLi或PDO,可以使用它們。 –

+0

變量'$ expense_id'和'$ invoice_id'定義在哪裏? –

+1

'$ columnValues'是一個數組。你一定需要使用'implode'將它傳遞給查詢文本。 –

回答

0

我想這樣的事情應該工作:

$columnValues = Array(); 

while ($row = mysql_fetch_assoc($head_qry)) { 
    $columnValues[] = $row['columnname']; 
} 
$filename = "uploads/reports/".$invoice_id.".csv"; 
$file = fopen($filename, 'w+'); 

fputcsv($file,$columnValues); 

// don't use `array_keys` 
$columnValuesStr = implode(', ', $columnValues); 

$data_qry = "SELECT $columnValuesStr from invoice_detail where invoice_id='$invoice_id'"; 

$data_result = mysql_query($data_qry); 
while ($result = mysql_fetch_assoc($data_result)) { 
    // `$result` already an array which holds values of selected fields, 
    // you can pass it directly to `fputcsv` 
    fputcsv($file, $result); 
} 
+0

非常感謝。它的效果很好。 – davidb