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

Open browser page depending on XML results
Hello,

I have some PHP code that sends webbased from data to an external url ( in the form of

The type or namespace name 'ServiceModel' does not exist in the namespace 'System'
When I locally run the website, it works just fine, but when I uploaded it to the hosting environmen

add to sql result
ok see rite now my sites hit counter is counted from the mysql visitor log i need to clear it aft

I think i'm using the syntax incorrectly
Hi Everyone!

I'm new to this forum and a newbie with PHP - I'm glad I found this site - I hop

Unexpected T_Variable ?
Hi all,
I dont really know what I am doing!! I know I'm doing something wrong, and I know its on

getting most records by count
Code: [Select]<?php

$connect = mysql_connect("localhost","dam

Curl & sessions PLS HELP
Hello,

I have a problem with curl and sessions and i will try to explain the best i could.

post to self
Trying to get my form to submit to itself. However I am also trying to use an image for my submit bu

order by date not ID number help php
I am trying to orginize the following code to order by date not id number.
any help would be grea

some query on multilingual website
Hi all,

Which is the simplest and easiest method to make a website multilingual,
is it put

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