0

I'm having a big headache with special chars ; let me explain.

I'm using PDO with MySql, here is my sample code :

$conexao = new \PDO('mysql:' .     'host=myhost;dbname=mydbname;charset=utf8'
            , 'myuser', 'mypass');
$conexao->setAttribute(\PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES utf8");
$sth = $conexao->prepare('select * from usuario');
$sth->execute();
$res = $sth->fetchAll(\PDO::FETCH_ASSOC);
var_dump($res);

This code alone will output the data correctly, with all special chars in table rows.

But if i use this code with the html tag for utf8, all special chars transforms into a � when rendered to browser. Here is my tag :

<meta charset="utf-8" />

If i remove this tag, the data is displayed correctly again, but all special chars of my html is messed up, except the data that comes from PDO.

The charset of my DB was 'latin1', but i changed it to 'utf8', without any changes.

To make things stranger, in my development enviroment this problem does NOT happen ; only in the deployed application. What i've found out is the PHP version in web-server is older than the one in my development environment.

What is wrong here ?

Thanks !

delphirules
  • 6,443
  • 17
  • 59
  • 108
  • 1
    possible duplicate of [UTF-8 all the way through](http://stackoverflow.com/questions/279170/utf-8-all-the-way-through) – hjpotter92 Jul 06 '14 at 16:01
  • `SET NAMES utf8` is redundant (in the best case), just get rid of it. Anyway, it isn't clear if you're asking how to use UTF-8 or if you have corrupted data into your DB. Can you please verify the encoding of a know string with MySQL's `HEX()` function? – Álvaro González Jul 06 '14 at 16:03
  • I don't have corrupted data, as i said in the post, if i use only the data extraction from the DB, withtout the meta tag in html, the DB data is shown corectly. – delphirules Jul 06 '14 at 16:56
  • 1
    Your data is not UTF-8 encoded. Simply changing a column from latin1 to utf8 will not re-encode your data. – cOle2 Jul 06 '14 at 17:06
  • Is there a way to re-encode the table data ? – delphirules Jul 06 '14 at 17:10

1 Answers1

0

add header in the top of your php script

header('Content-Type: text/html; charset=utf-8');

style007
  • 1
  • 1