开发者

Possible to loop "static" data in mysql loop

As you can see below I am pulling information from a database and writting it to a text file in a structured format (Thanks to everyone who has helped me out).

// 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 = 开发者_JAVA技巧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);
?>

There are a few things that need to be added in it's separate column that is not in the database. Mainly just bit of text like "bob's cards" . I was wondering if it is possible to add that into the mix and have it loop through. Or is it just simpler to add it to the database?


You can have MySQL write the data directly to a file using

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 

!! Note the use of forward slashes even on Windows !!

And please replace that ugly implicit WHERE join by an explicit INNER JOIN; it will make future alterations to that query much easier to debug.

Links: http://dev.mysql.com/doc/refman/5.1/en/select.html
And for the options to SELECT .. INTO OUTFILE see: http://dev.mysql.com/doc/refman/5.1/en/load-data.html


You can add normal text in the second argument of fprintf or you can add variables that do not have to be related to your database row using for example %s for strings (see here for other formats). Just take care, if you want to add a % sign, you will have to escape it.

For the structured format you are using, you will probably want to put your text in variables and use the same type of formatting you are already using for the database values.

Example for the header row:

$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");

Notice that I added the variable at the end of the second argument of fprintf.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜