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

LIMIT $start, 10... how to pass last value queried into next page with GET??
Ok I know how to display the first or last 10 results of a query...

$result = mysql_query(&q

Fetching array then reversing it
Hi, I have a simple problem, I'll try to explain it as best I can:
News entries in my database ar

Number Format
Hi All,

I have number '000000000050085' I want to format it to 500.85 Can any one give me

pls clear my confusion
Hi friends,

Pls solve my query .

what is the exact use of Scope Resolution Operator( i

update 2 columns by doing inner 2-column query
Hi,
is something like this possible?

update contract_all set col1,col2 =
(

pass form variables straight to email, no database required?
hello all,

im working on this form...

http://www.adobedayevents.com/project_request/pr

how do i make new line after *
First check this page here. and you see my report. Im pulling form a mysql db. I want to beable to m

Rand() help needed
Hi all,

Can someone explain and give me a quick example of how I would go about this?

Help with writing "$" with fopen
I just can't get my syntax correct. Could someone help me please? I am trying to write a connect fil

Time script, set to my time zone?
I am using this line to get the date and time

Code: $time = date(F." ".d.", &q

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