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:

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

CHMOD script
Hi,

I need a script to read all files in a folder and set to 777.

Can anyone help out

EU VAT Package 2010
Does any one know whether SAP will be developing new reporting functionality due the new VAT rules t

How to search for several parameters from objects in a database?
I have a database with lots of information about objects.
Now I would like to search for 4 or 5 p

Require select-option functionality in Module Pool Programming
Hi Gurus,

I am doing a development by Module Pool on Warehouse Management. For that devel

help with image text
Hi ...

see i need the text of the name and number to start in the center and always be in the

Problems with strings containing
Hey all,

I have encountered something strange in a script. I am trying to write an XML heade

Splitting Attributes
SQL> SELECT I_NAME, substr(I_NAME,1,instr(I_NAME,'O')) "First part",

substr(I_NAME, IN

for some reason mysql query not working, not inserting, please check it out
This code is not inserting anything into my db, don't know why, the $_SESSION variable does contain

Do While statement
hi guys,

This may sound trivial but im new to php and as part of an assignmenti have to const

Working with Dates, help.
Sooo to make a long story short, here's what im trying to accomplish.

I need to create a drop

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