2011-05-19 59 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