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

Forms Authentication and Refresh at Login page
Hello, When I try to press the Login button in my webapplication at my login.aspx page nothing h

Parse error: syntax error, unexpected $end in
hello,
i receive the error :Parse error: syntax error, unexpected $end in C:xamppxampphtdocsh

Files in current folder. Should be an easy fix.
Never mind. I've asked about this before and just found my answer. Anyway to delete this?

radio button reamains checked
Hello i'm trying to keep the state off my radio buttons so it shows which ones where clicked after t

JQuery, Masterpage, and Control issue
Hey everyone, I am using JQuery in several sites so I thought it would be best to place the library

DOMDocument
Hello All,

I need to take an XML document, modify some of the nodes in it and then perform a

Help please - How to validate from 2 possible answers
Hi

I hope somebody can help me with what will probably be really simple, I'm pulling my hair

ORA-00932: inconsistent datatypes: expected - got CLOB
SO : windows xp
database : XE

there is a table (transito) with two fields of clob

The page should be expire when cilck back button
hi,
i'm new to php world.
i create user registration page.
when i submit it,data goes to my

ImageCreate()
When I create an image and add text to it I want my text to be replaced with a PNG image, because th

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