mpar612 <mp*****@gmail.comwrote:
Hello,
I'm sort of new to PHP. I am using the following code to retrieve a
column from a database and to put all of the results into a .csv
file. This allows creates a .csv file, but only lists the first
result from the database. It is not returning all of the rows. I
know the issue is somewhere in my "foreach" but I'm not sure where.
Any help would be great. Thanks!
<?php
$selectSql = "SELECT artist_name FROM lounge_products";
$selects = $db->getAll($selectSql);
foreach($selects as $select) {
$content = $select[artist_name].",";
Concat:
$content .= $select[artist_name].",";
In the current code you keep overwriting $concat with the new value.
If you db object returns an array, this would be simpler:
$content = implode(',',$selects);
Now, all this code will not help you if an artists name contains a comma,
all your logic is lost.
For creating CSV's, I'd use this:
header("Content-Disposition: attachment; filename=export.csv");
$selectSql = "SELECT artist_name FROM lounge_products";
$selects = $db->getAll($selectSql);
$out = fopen('php://output','w');
foreach($selects as $select) fputcsv($out,$select);
Alternatively, use mysql's built in option to export a file, which would
also take care of escaping:
$file = '/path/to/file';
mysql_query("SELECT artist_name
INTO OUTFILE '{$file}'
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '\"'
LINES TERMINATED BY '\n'
FROM lounge_products");
header("Content-Disposition: attachment; filename=export.csv");
readfile($file);
--
Rik Wasmus
Posted on Usenet, not any forum you might see this in.
Ask Smart Questions:
http://tinyurl.com/anel