2017-07-30 9 views
0

iam phpの新機能ですが、静的な列を持つmysql結果をcsvにエクスポートする方法を知っていますが、列名を指定せずに動的にエクスポートする必要があります。私はこれを試してみました、私はこの仕事をしてください助けが必要です。動的列を持つ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

関連する問題