Write & Read UTF-8 from Mysql

The following php script shows how we can write and read Greek characters in a mysql database. Before starting check the encoding of your file. If you are using Zend studio go to Edit->Set Encoding and select Other: utf-8. Now in your php script after establishing a connection to the database type the following queries in order to set the names and characters equal to utf-8 for the specified connection, for me is just one connection so I do not use the resource as a parameter.

mysql_query(“SET NAMES ‘utf8′”);
mysql_query(“SET CHARACTER SET ‘utf8′”);

Next you can type you insert query:

$query = sprintf(‘INSERT INTO test (text) VALUES (“%s”)’, ‘write greek text here’);

And finally you can start reading from your database:

$q = mysql_query(“select text from test order by text”");
$row = mysql_fetch_object($q);

echo $row->text;
$row = mysql_fetch_object($q);

This small piece of information can save you a lot of time when trying to handle utf-8 characters. Good luck.

Leave a Reply