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

I am stumped
OK. Here is what I am trying to do. I have the conditions set, and if the conditions are met, I want

rookie looking for help coding a CSS form with PHP
I'm trying to figure out how to add PHP code to my xhtml form so that it is a working form embedded

TemplatePower & AJAX
Hi all,



I'm currently implementing some AJAX features in my PHP-framework (which is b

Batch Session SM35 stuck in status 'in Background
Hi Experts,

I am facing a problem with Batch Input session SM35.

The batch se

gmdate() - want 1 hr before time
Hi,
I am using php gmdate().
Now I am entering all dates in my dbase using gmdate("Y-m-d

some questions
Hello,

I am looking for the answers for following questions:

1) Does PHP support overl

urldecode question
How would I format this line of code properly?

<?php echo urldecode($_GET['Title']); ?

Convert Binary String to Decimal
Trying to Get:
Decimal: 305419896

Out of:
Binary String: xV4

Dump with added_funcion cl_salv_table
Hi there, I'm having some troubles adding a self defined function to an ALV in fullscreen. The thing

Multiple arrays inside data
Hi,

Simple question. I have a column called "array" in my database, and inserted in

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