utf8 decode/encode help needed

utf8 decode/encode help needed

by Joseph Rézeau -
Number of replies: 3
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers Picture of Testers Picture of Translators
Help needed from php & mysql gurus (not directly concerning Moodle).
I am currently adapting a php/mysql photo gallery piece of software to put a php version of my herbarium on line. Since a number of strings will be in French, I am using utf8 throughout, but I am confronted with a tedious problem, which may have a simple solution.
1- My mysql database collation is utf8_general_ci.
2- The HTML output from php is set to
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
3- When I write to the database field a string which has French characters in it, in order to get it displayed correctly (e.g. when I view the database using phpMyAdmin), I use mysql_query("INSERT INTO etc."), but previously I use utf8_decode for all my strings.
4- When I retrieve data from the mysql database, before displaying it, I have to pass each string through an utf8_encode for correct display in the browser.
Why is that? Given points 1 and 2 I would expect not to have to use those utf8_decode/encode functions.
Any help appreciated,
Joseph

Average of ratings: -
In reply to Joseph Rézeau

Re: utf8 decode/encode help needed

by Joseph Rézeau -
Picture of Core developers Picture of Particularly helpful Moodlers Picture of Plugin developers Picture of Testers Picture of Translators
Got it (I should have done more thorough research on the Web before asking)!
Each time I have a mysql_connect in a php file, I have added a mysql_query("SET NAMES 'UTF8'");
It does the trick: strings with diacritics are correctly displayed in the database and I no longer have to use utf8_decode or utf8_encode throughout my code.
Joseph
PS.- Moodle does that in files \lib\dml\mysqli_adodb_moodle_database.php and \lib\dml\postgres7_adodb_moodle_database.php, but maybe it also uses another mechanism somewhere else?
In reply to Joseph Rézeau

Re: utf8 decode/encode help needed

by Eloy Lafuente (stronk7) -
Picture of Core developers Picture of Documentation writers Picture of Moodle HQ Picture of Peer reviewers Picture of Plugin developers Picture of Testers
Nope, that's all you need to do (you found it! cool ). That command sets everything (client, connection and results) in utf-8 that is, exactly the encoding you're using in the php side (as far as all your pages are declared explicitly as utf-8) and mysql side (as far as that's the encoding for your db/tables/fields).

So, using it is enough to guarantee that utf-8 data from php will go straight to the mysql tables and the opposite without any conversion.

Ciao smile