简体   繁体   English

PDO MySQL UTF-8:从数据库读取的数据无法正确显示

[英]PDO MySQL UTF-8: Data read from database not showing correctly

show variables : show variables

character_set_client        utf8
character_set_connection    utf8
character_set_database      utf8
character_set_filesystem    binary
character_set_results       utf8
character_set_server        latin1
character_set_system        utf8
collation_connection        utf8_general_ci
collation_database          utf8_unicode_ci
collation_server            latin1_swedish_ci

Data inserted is UTF-8 and shows correctly in the database, html header is set to utf-8, meta-tag is set to utf-8. 插入的数据是UTF-8并在数据库中正确显示,html header设置为utf-8,meta-tag设置为utf-8。 All the content on the site (not coming from database) shows correctly), just not the content from the database. 站点上的所有内容(不是来自数据库)都显示正确),而不是数据库中的内容。

Connection (PDO): 连接(PDO):

$pdo = new PDO("mysql:host=$hostname;dbname=$database;charset=utf8",$username,$password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

So, I assume it has something to do with the output of show variables as it shows that the server's character set and collation are not utf-8? 所以,我认为它与show variables的输出有关,因为它表明服务器的字符集和校对不是utf-8? However, I run other sites on the same local server without any problems. 但是,我在同一本地服务器上运行其他站点没有任何问题。 Any idea where I could look to get it right? 知道我在哪里可以做到正确吗?

In your PDO connection: 在您的PDO连接中:

new PDO(
    "mysql:host=$hostname;dbname=$database;charset=utf8",
                                           ############
    $username, $password, array(
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
                                         ##############
    )
);

You are making use of SQL SET NAMES utf8 which is deprecated. 您正在使用不推荐使用的SQL SET NAMES utf8 You should not use it any longer. 不应该再使用它了。 And actually you are already making use of the charset parameter in the PDO DSN string which is the recommended way: charset=utf8 . 实际上,您已经在PDO DSN字符串中使用了charset参数,这是推荐的方式: charset=utf8

Just remove the SET NAMES utf8 init command and you should be fine. 只需删除SET NAMES utf8 init命令就可以了。

new PDO(
    "mysql:host=$hostname;dbname=$database;charset=utf8",
    $username, $password
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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