2016-12-05 96 views
0

這是我的代碼,工作得很好。當我從瀏覽器調用這個文件時,它以CSV格式下載我的文件。如何在mysql的每行下載文件的末尾添加文本?

<?php 
/* vars for export */ 
// database record to be exported 
$db_record = 'people'; 
// optional where query 
$where = 'WHERE 1 ORDER BY 1'; 
// filename for export 
$csv_filename = 'exported.csv'; 
// database variables 
$hostname = "localhost"; 
$user = "root"; 
$password = ""; 
$database = "db1"; 

// Database connecten voor alle services 
mysql_connect($hostname, $user, $password) 
or die('Could not connect: ' . mysql_error()); 

mysql_select_db($database) 
or die ('Could not select database ' . mysql_error()); 
// create empty variable to be filled with export data 
$csv_export = ''; 
// query to get data from database 
$query = mysql_query("SELECT * FROM ".$db_record." ".$where); 
$field = mysql_num_fields($query); 
// create line with field names 
for($i = 0; $i < $field; $i++) { 
    $csv_export.= mysql_field_name($query,$i).';'; 
} 
// newline (seems to work both on Linux & Windows servers) 
$csv_export.= ' 
'; 
// loop through database query and fill export variable 
while($row = mysql_fetch_array($query)) { 
    // create line with field values 
    for($i = 0; $i < $field; $i++) { 
    $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";'; 
    } 
    $csv_export.= ' 
'; 
} 
// Export the data and prompt a csv file for download 
header("Content-type: text/x-csv"); 
header("Content-Disposition: attachment; filename=".$csv_filename.""); 
echo($csv_export); 
?> 

假設生成的文件是這樣的:

"name", "age", "country" 
"Gulizer", "21", "Kurdistan" 
"Pierre", "20", "France" 

我要的是retreive年齡再次把它放在每行有一些文字像

"name", "age", "country", "text_added" 
"Gulizer", "21", "Kurdistan", "The age of Gulizer is 21" 

可能嗎?

+0

SELECT INTO OUTFILE有什麼問題? – e4c5

+0

什麼都沒有。它很好用 –

+0

每次你使用[mysql_'](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) 在新代碼中的數據庫擴展 ** [一隻小貓被勒死在世界的某個地方](http://2.bp.blogspot.com/-zCT6jizimfI/UjJ5UTb_BeI/AAAAAAAACgg/AS6XCd6aNdg/s1600/luna_getting_strangled.jpg)**它被棄用並且已經有多年並在PHP7中永遠消失。 如果您只是學習PHP,請花些精力學習'PDO'或'mysqli'數據庫擴展。 [從這裏開始](http://php.net/manual/en/book.pdo.php) – RiggsFolly

回答

0

我找到了解決辦法通過自己和大家分享一下

我剛過

for($i = 0; $i < $field; $i++) {$csv_export.= mysql_field_name($query,$i).';';} 
$csv_export.= '\n'; 

添加

echo "text_added;"; 

,改變

for($i = 0; $i < $field; $i++) { 
    $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";'; 
    } 
    $csv_export.= ' 
'; 
} 

 for($i = 0; $i < $field; $i++) { $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";'; } 
$csv_export.= ' 
'.$row['age'].'years old";'; 
} 

,最後我得到了這樣的結果:

text_added;name;age;country 
"21 years old"; "Gulizer"; "21"; "Kurdistan" 
"20 years old"; "Pierre"; "20"; "France"; 

正是我想要的。

相關問題