/    Sign up×
Community /Pin to ProfileBookmark

MySQL dump to spreadsheet file

I am trying to get some generic code to work, which will take a table and dump the elements into a tab delimited file that can then be opened in a spreadsheet.

I think I am getting close with this:

[CODE]$query = mysql_query(“SELECT * FROM `members`”);
while ($row = mysql_fetch_array($query)) {
foreach ($row as $element) $output .= $element.”t”;
$output .= “rn”;
@file_put_contents($file,$output,FILE_APPEND|LOCK_EX);
unset($output);
}[/CODE]

It works except each row in the file has each element twice. I don’t see how that is happening. All the elements are there and all the rows are in separate lines as I want. But each line has each element value twice.

The other thing I would like to do is have a first row with the element name. I figure that would take another query initially as the first line in the output file, then start over with the code above. But I am not sure how to extract the element names in the row.

Any help would be greatly appreciated.

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogApr 03.2011 — I would recommend outputting it as a CSV file. (If you really need to have tabs, just use the optional 3rd arg of fputcsv() to use "t" as the delimiter.)

Untested:
[code=php]
$fh = fopen($file, 'w');
if($fh == false) {
die('fopen problem');
}
$row = mysql_fetch_assoc($query);
fputcsv($fh, array_keys($row)); // print column names
mysql_data_seek($query, 0); // back to first record
while($row = mysql_fetch_assoc($query)) {
fputcsv($fh, $row);
}
fclose($fh);
[/code]
Copy linkTweet thisAlerts:
@Beach_BumauthorApr 03.2011 — Works perfect. Thank you.
×

Success!

Help @Beach_Bum spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,
)...