Export data to CSV file using MySQL query (data contains single and double quote)

It is really straight forward to export data from your database to CSV file. However, when your data contains some special characters such as single or double quote, it could destroy your CSV file’s structure completely and end up of messy CSV fiel content.

This code would help

SELECT authorname, authoremail, REPLACE(REPLACE(content,'"',''),"'","") as escapeContent , datecreated FROM feedback_table WHERE content IS NOT NULL AND content <> '' ORDER BY datecreated DESC
INTO OUTFILE './feedback.csv'
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'

In the previous example of code it simply remove all single and double quote from the content column. It is not good practice in some case, but you could also can use the backslash.

 REPLACE(REPLACE(content,'"','\\"'),"'","\\'")

You might interested in all Related Posts

This entry was posted in Web development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">