How to fix and store Unicode in MySQL using PHP

One obstacle about programming is learning how to code, and then a whole new level for people dealing with bi-lingual and non-Latin applications is the Unicode issue. I sometimes spend more time trying to figure out how to solve something so silly like how to store unicode in mysql using php more than coding the whole thing! That’s why I thought I’d make this quick article about how to fix unicode in a mysql database.

Store unicode in mysql

The steps are so simple and you’ll solve this in a couple on minutes 😉

How to Fix and Store Unicode in MySQL using PHP

Changing the datatype in MySQL tables to the correct Unicode:

By default, MySQL makes all tables and the Collation as utf8_unicode_ci. You should change this for all your unicode columns to utf8_general_ci.

unicode in mysql


Making your PHP database connection Unicode compatible:

This also was a tricky part that I couldn’t find many resources online talking about it (or how to do it). You should set the charset to utf8 in order to be able to store Arabic, Hebrew, Indian, or any Unicode language using PHP.

This is how I usually set up my MySQL connection using PHP:

@mysql_connect($DB_host, $DB_user, $DB_pass) or die("Could not connect!");
@mysql_select_db($DB_name) or die("Could not select database!");

The trick to fix the Unicode issue is by simply adding mysql_set_charset('utf8'); after establishing the connection. So it will be like this:

@mysql_connect($DB_host, $DB_user, $DB_pass) or die("Could not connect!");
@mysql_select_db($DB_name) or die("Could not select database!");


Storing your PHP file using Unicode encoding

This is the last step and it’s also not mentioned usually. It’s so simple. using your code editor, change the encoding of your php file to Unicode. Each code editor is different but here’s where it is in NotePad++:

Unicode notepad++



And if you’re trying to display a non-Latin language in the browser, you should of course not forget to add this code to the head tag:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

Also this attribute to your form tags:


That’s all you need to successfully store Unicode in MySQL using PHP! Tell me if this has helped you or if you had any problems. And feel free to share this article to make someone else’s life easier 🙂


Comments (5)

Leave a Reply