Convert array to string and write to csv file


Posted on 16th Feb 2014 07:03 pm by admin

I am looking to write a MySQL query to a csv file.

At the minute I:

Did you know?Explore Trending and Topic pages for more stories like this.
check for the original file, and delete it;
create a new (blank) file;
run the MySQL query and pass it into an array;
write it to the new file;

But it is missing something, as it only writes the first line from the query.

my code so far is:

Code: <?php

//Delete Original File
...

//Set variables
$uName = "root";
$pWord = "password";
$host = "localhost";

$Query = "[i]...MySQL query...[/i]";

$Filename = str_replace('.php', '', basename("Report")) . '_' . date("Ymdhis") . '.csv';

$ReportFiles = "c:ReportFiles\";

$Newfile = $ReportFiles.$Filename;

$cr = "n";

//Create a new (empty) file
echo exec("<nul (set/p z=) > "$Newfile"");

//Run MySQL Query
$connection = mysql_connect($host, $uName, $pWord) ;
mysql_select_db("dbName", $connection) ;
$result = mysql_query ($Query, $connection);
while ($row = mysql_fetch_array($result, MYSQL_NUM))
$String = implode(",",$row);
{

//Open file and save contents of query to that file
$fp = fopen($Newfile,"a");
if($fp){
fwrite($fp,$String.$cr);
fclose($fp);
echo "File saved successfully";
} else {
echo "Error saving file!";
}
}
?>
No comments posted yet

Your Answer:

Login to answer
239 Like 46 Dislike
Previous forums Next forums
Other forums

Multiple while loops
I have several DB queries that I know should be returning results and aren't. I have a feeling it ha

Help With Showing Users On the Index Page
Ive got this code which works just how i want it to.

Code: <?
$timenow=time();

Get to know your fellow coder
I think it's time we got personal around here. There's a lot of code swapping and a few members kno

Post PHP form to non-existing page
The company that I work for host their PHP code on IIS on a Windows server, no Apache, so no mod_rew

Xml parsing
I need a suggestion about parsing xml with multiply parts like pervious...
i.e. different device

"SEO" URLs
Hey, I'm wondering how to go about creating and using these types of URLs. I'm presuming it's PHP th

How to change www in url with a specified name
Hi
I'm trying to change the url http://www.sitename.com/apparels to something like below
http:

upload photo limits
ive got a upload photo script and im just trying to make more secure currently it limits size and as

php mysql script to find record
Hi,

Currently I have a simple table with 4 columns. A, B, C, D

If I want to find all

Multi image upload
I have a gallery to build and want to build a dynamic upload form to allow for $var number of fields

Sign up to write
Sign up now if you have flare of writing..
Login   |   Register
Follow Us
Indyaspeak @ Facebook Indyaspeak @ Twitter Indyaspeak @ Pinterest RSS



Play Free Quiz and Win Cash