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

PHP switch function help
Hi, I am trying to create a search function for a directory website. On the search function on html

Escape Latin Characters
I need to escape latin characters in an xml doc. Example: "é" is escaped to "é". I thoug

compile php5 with DOM
Hi,

I can't manage to compile php 5.3.0 from source on Windows to include DOM,
in spite of

remove trailing slash from array
I have the following array which contains trailing slashes I need to remove. What is the best way to

mysql UNION | warning mysql_fetch_array !!
Code: <?php
$i = 0;
$query1="SELECT * FROM `products` WHERE `div

PayPal Redirect Issue
When I have my paypal button set so that is redirects to http://empiremarketing.ca/order.php,it work

need good snippet manager
Hi. as i am coding and learning more, it is becoming difficult to manage code snippets. how you mana

UTL File problem
Hi
I have a file in certain path with the following permissions (The file is a dummy file witho

dinamic "textboxes"?
Ey all, my first post here, i hope its not a hard one

I display mysql results in a table

opening a window with after form submission
I know this this forum has nothing to do with JS, but i'm trying to use it with my php script.
<

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