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

PHP Directory Listing Not working
Hey Guys,

I need help, I tried a ton of directory listing scripts and they all don't work. Al

SAP Treasury - Commodities
We are running SAP ECC 6.0 with Treasury Activated.
EA-FIN is also activated (SFW5).

Typing math
I've added support for typesetting math using LaTeX on the forums.

Example:
Code: [Select]

PHP FTP Can't upload Big FIles
Anyone had any success using FTP to upload a file say 90m?

im using ftp_put and it returns fa

email form (cannot find the problem)
Hello there. I've been having trouble with an email form. Can't find the problem really. I've tested

Pro-rata Billing in Periodic Billing for Rental
Hi guys,

We have a situation, where a rental contract starts at the mid of the month say

Having Problem with Date
l have a submit buttom where user have the possibility to add a date to specify when his message s

How to form a xml form table with a single sql statement..?
Hi everyone,
I don't know if this is going to be a duplicate thread but i couldn't

Not showing whole name with mail () script
I sent up a simple mail form with the PHP mail() script. One problem is when it sends an email with

Production of mango in processing industry
Hi,

We have one scenario ,company is in process industry,they are manufacturing MANGO pul

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