2011-05-19 68 views
0

正如您在下面看到的,我從數據庫中提取信息並將其寫入結構化格式的文本文件(感謝所有幫助我的人)。可能在mysql循環中循環「靜態」數據

// Query the database for data 
$query = "SELECT cards.card_id,title,description,meta_description,seo_keywords,price FROM cards,card_cheapest WHERE cards.card_id = card_cheapest.card_id ORDER BY card_id"; 
$result = mysql_query($query); 

$result = mysql_query($query); 

// Open file for writing 
$myFile = "googleproducts.txt"; 
$fh = fopen($myFile, 'w') or die("can't open file"); 

// Loop through returned data and write (append) directly to file 
fprintf($fh, "%-10s %-50s %-450s %-50s %-300s\n", "id", "label","description","price","seo keywords"); 
fprintf($fh, "\n"); 
while ($row = mysql_fetch_assoc($result)) { 
fprintf($fh, "%-10s %-50s %-450s %-50s %-300s\n", $row['card_id'], $row['title'], $row['description'],$row['price'], $row['seo_keywords']); 
} 

// Close out the file 
fclose($fh); 
?> 

有一些事情需要添加到它不在數據庫中的單獨列中。主要只是一些文本,如「鮑勃的卡片」。我想知道是否有可能將它添加到混音中並讓它循環播放。或者只是將它添加到數據庫更簡單?

+2

你爲什麼'$結果= mysql_query($查詢); $ result = mysql_query($ query);'連續查詢數據庫兩次? – Johan 2011-05-19 14:26:16

回答

0

你可以擁有的MySQL使用

SELECT cards.card_id 
    ,title 
    ,description 
    ,meta_description 
    ,seo_keywords 
    ,price 
INTO OUTFILE 'c:/dir/test.txt' FIELDS ESCAPED BY ' ' FIELD ENCLOSED BY '"' 
FROM cards 
INNER JOIN card_cheapest ON (cards.card_id = card_cheapest.card_id) 
ORDER BY card_id 

直接將數據寫入一個文件!請注意即使在Windows上也使用正斜槓!

並請用明確的INNER JOIN代替那個難看的隱含的WHERE連接;它將使未來對該查詢的更改更容易調試。

鏈接:http://dev.mysql.com/doc/refman/5.1/en/select.html
而對於選項SELECT .. INTO OUTFILE見:http://dev.mysql.com/doc/refman/5.1/en/load-data.html

0

您可以在fprintf的第二個參數中添加普通文本,或者可以使用字符串(see here for other formats)爲例如%s添加不必與數據庫行相關的變量。只要保重,如果你想添加一個%的標誌,你將不得不逃脫它。

對於您正在使用的結構化格式,您可能希望將文本放入變量中,並使用與數據庫值相同的格式。

實施例的標題行:我添加變量在fprintf的第二個參數的端

$bob = "bobs cards"; 
// Loop through returned data and write (append) directly to file 
fprintf($fh, "%-10s %-50s %-450s %-50s %-300s %-50s\n", "id", "label","description","price","seo keywords",$bob); 
fprintf($fh, "\n"); 

的通知。

+0

所以基本上就像$ bob =「bobs cards」;然後在「行」的最後添加$ bob? – 2011-05-19 14:33:02