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

Send inserts to mysql thru port 80
Hi!

I have an application that must do some inserts in a mysql db. This db is behind a firewa

Working with popups and such in a class
I've recently started building my applications completely enclosed in classes. I like the fact that

Aris, Netweaver BPM, Visual composer and X'app
Dear Experts,

Whats the relationship between the following components: Aris, Netweaver BP

Open/Close Links in Php
Hello, Hoping someone can inform me how I can get PHP to automatically open a set of links in a new

Inserting multiple records from single form
I've found a number of threads that deal with this issue, but I'm new to php and coding language so

Mysterious Timeouts
I've deployed a few simple AJAX-enabled web page to a local server that is accessed through the Inte

isset undefined variable
Hi all,

Hope someone can point out the obvious. I've a log in script, if you dont enter a use

BAPI BBP_INB_DELIVERY_CREATE - material number missing in delivery
Hi Experts,

I was able to successfully create an Inbound delivery with reference to a PO

PHP Script runs on CLI but not through web browser
I am running into an issue that I just can't seem to find the answer to. I have a Windows Server 200

Displaying image from database
Hi,

I've got a site where that's got a database behind it. Currently it has loads of items in

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