简体   繁体   中英

PDO x MySQL x HTML charset issue

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 !

add header in the top of your php script

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM