2017-03-24 16 views
0

PHPを使用してMySQLクエリの結果をファイルに書き込む際に問題があります。検索結果は間違いなく、ファイルが作成されますが、ファイルを開くと空になります。私はそれがファイルへの書き込み方法と関係があると思うが、わからない。PHPのMySQLクエリ結果をCSVファイルに出力する

$result = mysql_query($compsel); 
if(!result) die("unable to process query: " . mysql_error()); 
$fp = fopen('results.csv','w'); 
mysql_data_seek($result,0); //set data pointer to 0 
$rw = mysql_fetch_array($result, MYSQL_ASSOC); 
print_r($rw); 
foreach ($rw as $fields){ 
    fputcsv($fp, $fields); 
} 
fclose($fp); 

ありがとうございます!

答えて

1

はここに例を示します

// output headers so that the file is downloaded rather than displayed 
header('Content-Type: text/csv; charset=utf-8'); 
header('Content-Disposition: attachment; filename=data.csv'); 

// create a file pointer connected to the output stream 
$output = fopen('php://output', 'w'); 

// output the column headings 
fputcsv($output, array('Column 1', 'Column 2', 'Column 3')); 

// fetch the data 
mysql_connect('localhost', 'username', 'password'); 
mysql_select_db('database'); 
$rows = mysql_query('SELECT field1,field2,field3 FROM table'); 

// loop over the rows, outputting them 
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row); 

あなたは、あなたのニーズに合わせて変更することができます。 出典:http://code.stephenmorley.org/php/creating-downloadable-csv-files/

+0

大変ありがとうございます。 – KittenMittons

関連する問題