Helmut
Helmut

Reputation: 1377

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

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. All the content on the site (not coming from database) shows correctly), just not the content from the database.

Connection (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? However, I run other sites on the same local server without any problems. Any idea where I could look to get it right?

Upvotes: 4

Views: 2103

Answers (1)

hakre
hakre

Reputation: 197554

In your PDO connection:

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. 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.

Just remove the SET NAMES utf8 init command and you should be fine.

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

Upvotes: 3

Related Questions