MySQL UTF-8 PDO: data read from a database that does not display 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 

The entered data is UTF-8 and correctly displayed in the database, the html header is set to utf-8, the meta tag is set to utf-8. All content on the site (not coming from the database) is displayed correctly), not content from the database.

Compound (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 that it has something to do with the output of show variables , since it shows that the server 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 right?

+4
source share
1 answer

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 using SQL SET NAMES utf8 , which is deprecated. You should not use it anymore. And in fact, you are already using the charset parameter in the PDO DSN line, which is the recommended way: charset=utf8 .

Just remove the SET NAMES utf8 init command and everything will be fine.

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

Source: https://habr.com/ru/post/1442852/


All Articles