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

Select Lists into MYSQL
Hello All, I am new to PHP @ 1 week. So borrowing code anywhere I can. I am making progress, but h

Undefined Variable: PHP_SELF, pls help
Hi,

Im a newbie on PHP / MySQL programming and Im running a script to search one field on my

IIS on 2003 anon access disabled issue
I have an IIS server that belongs to a domain, and anonymous access is turned off for all my sites.

need to add "sizes" to shopping cart
Hey guys, I am trying to figure out a way to add a "size" selector on to this bit of code.

WORDPRESS - Multiple Loops Only Going to One Post?
I have various pages with multiple loops and i need them to be individual to all other categories.

Removing Title From database problem
Hi again ! i am having an issue with updating database. When i update any price of a title it remove

License Issue - service type user
Hi,

I would like to understand the following issue regarding sap license.
I wish to

PHP template help
Ok, I don't know if anyone can help me but I am using PHP templates to make a site. I am a newbie an

Different actions for different parts of a string
<?php
function dosomething($string, $else = '') {
if (empty($else))
$string

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