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

Code Help.. If txt input box empty search X instead..
I am having a problem with my search script. At current it will simply search by a selected date whi

Problems with array
This code is the last lines in an upload script that uploads 4 images at the same time and writes th

PHP - HTTP Digest Authentication - Understanding Code Help
Hi Everyone,

This is my first time on your website and please excuse if I am asking silly que

help me fix these syntax errors...
I keep getting multiple syntax errors on this script like this one:

Parse error: syntax error

Async WSAConnect failed on XP with error code = 2 ("File not found")
Hi all,

I have very strange bug, please help me if you can.

It is reproduced o

array_combine() trouble w/csv file
I have a problem with a piece of code I wrote to import some records from a csv file into mysql. I h

Having a problem get the selected item from a drop down menu
I have been looking at this for days now.

I have a drop down menu that get it's values from a

PHP4 to PHP5 Conversion
Hi Everyone,

I am working on a site that is built up on PHP4 and each page is being started f

Problem with umlauts and UTF-8
Hello every1,

I'm creating my own little CMS at the moment and got some problems with the cha

Need help Updating SQL Server Express DB from c# :(
Please can anyone help with:-
1 How to sructure the strSelect statement.
2 How to instruct

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