473,385 Members | 1,587 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Exporting From MySQL to .csv using PHP

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].",";

}

Header("Content-Disposition: attachment; filename=export.csv");
print $content;
?>

Mar 7 '07 #1
4 3515
mpar612 wrote:
[...]only lists the first result from the database.
Nope - it lists the last one.
foreach($selects as $select) {

$content = $select[artist_name].",";
You are destroying the previous contents of $content at every iteration.

Try putting the header() up, and echoing things instead of putting them into
variables, or try the .= operator.
--
----------------------------------
Iván Sánchez Ortega -ivansanchez-algarroba-escomposlinux-punto-org-

Un ordenador no es un televisor ni un microondas, es una herramienta
compleja.
Mar 8 '07 #2
Rik
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
Mar 8 '07 #3
Excellent. Works perfectly. Thank you both for your help!

Mar 8 '07 #4
On Mar 8, 12:57 am, Iván Sánchez Ortega <ivansanchez-...@rroba-
escomposlinux.-.punto.-.orgwrote:
mpar612 wrote:
[...]only lists the first result from the database.

Nope - it lists the last one.
foreach($selects as $select) {
$content = $select[artist_name].",";

You are destroying the previous contents of $content at every iteration.

Try putting the header() up, and echoing things instead of putting them into
variables, or try the .= operator.

--
----------------------------------
Iván Sánchez Ortega -ivansanchez-algarroba-escomposlinux-punto-org-

Un ordenador no es un televisor ni un microondas, es una herramienta
compleja.
Dear mpar612,

if you need your results in that that array change your code e.g. to:

$i = 0;
foreach($selects as $select) {
$content[$i] = $select[artist_name].",";
$i++;
}

Good luck
Martin
------------------------------------------------
online accounting on bash bases
Online Einnahmen-Ausgaben-Rechnung
http://www.ea-geier.at
------------------------------------------------
m2m server software gmbh
http://www.m2m.at

Mar 8 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: b1cq7 | last post by:
I'm exporting MySQL data using a sql script containing:: SELECT * FROM (database name) INTO OUTFILE (filename) FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n'; The file...
1
by: Alban Gerome | last post by:
Hi there, I'm trying to export a pictures table, my mySQL database table already exists so I have linked both tables in Access and I tried to run a simple append query in Access to export the...
2
by: James Alexander Starritt | last post by:
I also posted similarly in mailing.database.mysql I have created a rather large (60 table database) website dealio in PHP that works with MS SQL Server, Oracle, MySQL and presumably any other...
2
by: Peter | last post by:
Hi all, Quite by accident, I found the mysqldump utility, that comes with MySQL, which dumps/backsup a database, table, or record. It looks very versatile! Does PHP have a way to export...
6
by: Kevin Chambers | last post by:
Hi all-- In an attempt to commit an Access MDB to a versioning system (subversion), I'm trying to figure out how to convert a jet table's metadata to text, a la SaveAsText. The end goal is to...
9
by: Bob Sanderson | last post by:
I'm trying to export a table to an ODBC database using a VBA subroutine. I have tested the ODBC setup manually and it works fine but when I try to do it with VBA, I get a "connection failed" error....
7
by: alf8kitty | last post by:
Hello, Im still very new to php and am having a problem. I return a MySQL query to a form in my php page and I want to be able to export the form data to Excel when the users clicks a link (or a...
1
by: cmgmyr | last post by:
Hey All, I'm having a little problem with exporting data from my database. The problem is that the query seems to be too much for PHP and MySQL to handle since it is timing out. I have the timeout...
0
zorgi
by: zorgi | last post by:
Hello guys Is there a way of exporting privileges tables from mysql database. I just need too transfer my developing database from one computer to another. Thanks
9
NawazAhmed
by: NawazAhmed | last post by:
Hi, I saw the same titled post but the answer given there is abt how to import data from an input file. I know this can be done once u can get data from database in ur application using java,.net...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.