Monday, May 24, 2010

How do I write a php/mysql query to csv?

How do I write a php/mysql query to csv? Thanks.

How do I write a php/mysql query to csv?
Hi there, here is how you could do it:





%26lt;?php





// Next Line Builds the first row of the CSV


$output = "\"Name\",\"Phone\",\"Email\" \n";


/* NOTE: REMOVE the space before \n on the end of the line above





Somehow on the preview I see that If I post it without that space, Yahoo is formatting it therefore changing how it's suppose to be. I hope you understand.


*/





Calldb(); // This function connects to the database


// I'm assuming you know how to connect to the database


// Use your own function or mysql connector here





$sql_query = "SELECT name, phone, email FROM contacts";


$result = mysql_query($sql_query) or die("There was a problem with the Database");


$number_of_records = mysql_num_rows($result); // Get number of records found





if($number_of_records)


{





While($rows = mysql_fetch_row($result))


{





$name = Trim($rows[0]);


$phone = Trim($rows[1]);


$email = trim($rows[2]);





$output .= "\"$name\",\"$phone\",\"$email\" \n";


// Adds to CSV





/* NOTE: REMOVE the space before \n on the end of the line


Somehow on the preview I see that If I post it without that space, Yahoo is formatting it therefore changing how it's suppose to be. I hope you understand. Same thing!


*/





}





}





$csv_filename = "CSV_Filename.cvs";





// Now save $output to a file


// MAKE SURE THE DIRECTORY HAS chmod PERMISSIONS to Write





$fp = fopen($csv_filename,"w");


fwrite($fp, $output, strlen($output));


fclose($fp);





echo "%26lt;a href=\"$csv_filename\"%26gt;Link to CSV FILE%26lt;/a%26gt; (Right-click and choose Save Target As)%26lt;br%26gt;";











?%26gt;








I hope that's what you were looking for. As you can see, you can format the output to be whatever you want and then save it to a file.
Reply:are you wanting the output to be CSV from a select statement?


No comments:

Post a Comment