-1

I thought I understood how charset worked but obviously not yet.

Using eclipse I create a new PHP project. I add an index.php file (very simple) :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
  <head>
<meta http-equiv="Content-Type" content="text/html charset=utf-8" />
  </head>
  <body>
    <?php
      try {
    $dbh = new PDO('mysql:host=localhost;dbname=symfony', 'root', '');
    foreach($dbh->query('SELECT * from product') as $row) {
    print_r($row['description'] ."</br/>");
    }
    $dbh = null;
      } catch (PDOException $e) {
    print "Erreur !: " . $e->getMessage() . "<br/>";
    die();
      }
   ?>
  </body>
</html>

the field 'description' is utf8_general

my database is utf8_general

I can read in phpMyAdmin that my database server charser UTF-8 Unicode (utf8)

I add the directive 'AddDefaultCharset utf-8' in the Apache config file

the charset in php file is utf-8

Anyway there is a problem with the accentuated letters.

To display them properly I can :

  • change Apache default charset : AddDefaultCharset iso-8851-1

OR

  • use the utf8_encode PHP function

My question is : considering that everything is UTF-8, when are my strings formatted in iso-8851-1 along the line of execution ?

mlwacosmos
  • 4,391
  • 16
  • 66
  • 114
  • 2
    You never tell PDO about UTF-8... – Álvaro González Oct 22 '13 at 14:51
  • Has the DB fields been saved to DB from a webpage encoded with ISO-8851-1 ? – jtheman Oct 22 '13 at 14:53
  • @ÁlvaroG.Vicario You are right, I thought that naturally PDO was encoding utf-8 but no so I added : new PDO('mysql:host=localhost;dbname=essai;charset=utf8', 'root', '')... it works... I could accept your answer – mlwacosmos Oct 22 '13 at 15:05
  • possible duplicate of [UTF-8 all the way through](http://stackoverflow.com/questions/279170/utf-8-all-the-way-through) – deceze Oct 22 '13 at 15:12

2 Answers2

3

Regarding UTF-8, Stack Overflow users have compiled a quite comprehensive check list at UTF-8 all the way through. In your case, the missing bit was that you weren't telling PDO about the connection encoding:

$dbh = new PDO('mysql:host=localhost;dbname=symfony', 'root', '');

... should be:

$dbh = new PDO('mysql:host=localhost;dbname=symfony;charset=utf8', 'root', '');

Please note that all other alternative ways to set such encoding (namely running SET NAMES utf8 either manually or with the PDO::MYSQL_ATTR_INIT_COMMAND parameter) are discouraged for PHP 5.3.6 or greater, when the charset parameter was added to the DSN.

Community
  • 1
  • 1
Álvaro González
  • 142,137
  • 41
  • 261
  • 360
0

You must also set the connexion as UFT-8

$dbh->query('SET NAMES utf8 COLLATE utf8_general')
Sébastien
  • 11,860
  • 11
  • 58
  • 78