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

if php cookie set, show code...
Hi all.. I need to figure out this little snippet right quick.. seems like it should be easy enough

Problem with variable declaration in switch statement
Hello, I am having some trouble assigning a value to a variable inside a switch statement. What I a

How to show more than 1 users with this code...
Hello,
i have a table that shows users only if I, as Administrator, want to be shown. But its sho

Change of partner analyse in sales orders
Hello,

I changed the partner analyse for sales orders and added a new mandatory partnerro

TimeStamp Column Problem...
I'm mad at my self and thinking I'm a little retarded. It just be some one mistake I'm missing here.

Solution to the FindControl problem
I have seen may posts about having problems with the FindControl method. Most seem to come about bec

Ajax not working on IE 6 for Windows CE
I've created a webpage which uses the classis Ajax in following format:view plaincopy to clipboardpr

Sort Alternative/bi-monthly
Hi all,

Am going mad trying to get something to work.

I'm creating a CMS for a magazi

same querie, or a new one??
Hi guys,

I'm still working on this drop down list. I've got the actual drop down list to wor

single values into sql field
i have a form which i want the user to able to select multiple answers. But i want the answers to be

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