scriptygoddess

07 Feb, 2003

mySQL data to CSV

Posted by: Jennifer In: Lessons learned

This isn't exactly useful for blog stuff – but if you're using mySQL for a business application, then downloading your data into a CSV file (CSV = Comma Seperated Values) is probably something that might come in handy. The key that I've found is that you can have any kind of characters inside each field, so long as you surround the data with double quotes. Of course, that presents the problem of, if your data uses double quotes, it will kind of mess things up. The solution I came up with was to take the data in the field, and replace the double quotes with two double qoutes (this indicates that it's part of the data and not the end of the field.)

So here's what your code will look like (what I did was store all the data in a string, then write the string to a file – this demonstrates how I create that string):

$query = "SELECT field1, field2, field3 FROM tablename";
$result = mysql_query($query);
$num_results = mysql_num_rows($result);<br>
//write header row
$stringToWrite = "\"field1\"","\"field2\"',"\"field3\""\n";<br>
for ($i=0; $i<$num_results; $i++) {
$row = mysql_fetch_array($result);
$stringToWrite .= "\"".str_replace("\"", "\"\"",$row["field1"])."\",\"".str_replace("\"", "\"\"",$row["field2"])."\",\"".str_replace("\"", "\"\"",$row["field3"])."\"\n";
}

1 Response to "mySQL data to CSV"

1 | Dave

July 6th, 2004 at 4:39 am

Avatar

Keep de following in mind, while getting data from the DB:
If you specify $row['fieldname'] you can run into problems, if you format the date (datetime field) within the query. So it might be a better solution, to call the rows like:

$row[0] (entry null of the array and so on…

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements