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
46
Other forums
php slowing my site?
Hi all,
I think that one of the reasons that my site doesn't work fast is that the code is ve
Display search result
Hi!
I have a SQL database with information about albums and track (music).
This is wh
DateObject and Nulls
Hi all,
I have an array mapped to a value object. One of the items in the array is a PHP Date
PHP5 - Verifying a secure mail is secure
I need to send an e-mail from a form to a external department and because it contains personal custo
Procedural to OOP
ohn Kleijn said that to avoid writing "crappy code", we should learn OOP and common OO pri
Output Buffering question
Hi all,
I've been trying to wrap my head around output buffering. So far I've found tons of
cURL Upload Help
OK, I am creating a bridge from a local program to my website and I am trying to find the best way t
Do While statement
hi guys,
This may sound trivial but im new to php and as part of an assignmenti have to const
Nested (echoed) php running wrong script
Got a problem with a php website I'm creating.
In a nutshell, the first page is entirely html
MySQL noob question
hi guys
I have a simple mysql table set up, along the lines of
Col 1 - Col 2 - Date_l