Adding special characters to MySQL

When you’re adding data to MySQL, you might experience that MySQL sometimes gives a SQL error in a code that normally works fine.

Typically this is caused by special characters like ‘ ” % in the new data, that conflicts with the SQL used to insert the data into the database. This post gives you some useful tips for handling this situation.

Escape the special characters

The workaround in this situation is typically to escape these special characters, so there is no conflict with the SQL.

In the text string:

Jack’s cafe & Barbeque

escaping the special characters means adding slashes like this:

Jack\’s cafe \& Barbeque

Adding slashes can be made by some kind of search-and-replace function in your script.

However if you’re using PHP, PHP can actually very easily do the trick for you. Just use the function addslashes() and PHP will automatically escape all special characters

$data = ‘Jack’s cafe & Barbeque’;

$escaped_data = addslashes($data);

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS
fold-left fold-right
About the author
Jørgen Nicolaisen has been passionately interested in everything online since 1995. His experience is based on working with small hobby projects as well as high volume websites. Jørgen is currently focused on the PHP based programming framework - Codeigniter, and WordPress naturally

Comments are closed.