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!";
}
}
?>

239 Like 46 Dislike
Previous php-forum Next php-forum
Other php-forum

mysql VARCHAR acting like INT
Hi, All.

I have a table that contains a varchar(10) column named weird_field. In this column

Undefined offset when using a flat file with pipe symbols
Hi, I've got a flat file/text file which I'm currently using as a member database for my site (not a

Return X values where an ID number doesnt matter
Well as for subject heading, thats the best i could think of.

Currently im having a problem w

replacements
I have a variable in my PHP script like

ASSFDDDDDDDDDDDDDASDDDDDDDDARYTRHKKHHHHHHHHHHH and p

unexpected T_STRING
error log "[Sat Jan 09 18:27:58 2010] [error] [client 127.0.0.1] PHP Parse error: syntax error

Add code to enable passing of checkbox variable on login
Ok, I have a login page, but want to add a checkbox that when checked and successful login is made i

Frustrated php Newbie
First off, I am pretty much a PHP nub. I can read and understand the language (most of the time) so

Apple's revamped lineup arrives

I'm personally curious about the magic mouse.. a multi-touch concept sounds like it could be nea

Curl timeout breaks script
So im having difficulties with skipping timeout error in curl
my script calls different functions

gmmktime or mktime
I live in the UK, i am within the GMT (with daylight saving time ie 1 hour difrence between summer a

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