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

Login Functionality Working Different on IE
This is an odd one, I have a site which has an admin section. The admin pages unsurprisingly require

Internal class functions don't seem to get executed.
Hi. Can someone please put me out of my misery on this. I don't write much PHP and this has me baffl

The IE or FF detector
Hello Friends,

Problem of today ( we seek for php help ) as following ,

we know all th

Unable to display contents in Second Drop Down Box
Hi All,

What I am trying to do is 2 dependent drop down boxes and when user selects su

How to use Ajax to verify data on a DB ?
Hello everyone, well i want to know how to check a value if it exists or not on a Data base and capt

b+ tree
Hi
can every body help me about b+ tree ?(insert & delete)

how to hide input fields on selection screen using variant attribute
Hello all,

I want to know how to hide input fields on selection screen using variant attr

Using Microsoft Exchange Server with PHP
Hi,

I wanted to know if its possible to fetch email attachments from the exchange server usin

Problem with passing variables
I'm not really a php programmer so I'm really struggling with this issue.

I have a banner s

Really need helps regarding Pagination with Sort
I need someone helps regarding pagination problem...i actually want to make my page limited to let s

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