简体   繁体   中英

Encoding: everything is UTF-8 but the DB output is displayed wrong. Any Ideas?

I know, there are plenty of questions about encoding but after checking a lot, the problem unfortunately still exists.

I exported the PHP/HTML-files (zip) and the MySQL-Dump (zip) from a Notebook to a PC (without using git). Every file is UTF-8 and every letter is displayed right in the Editor and in the database (PHPMyAdmin).

But when I open the project in any Browser, some letters (ä, ü, ü, ...) are displayed wrong.

In the HTML head I've this line for setting the charset:

<meta charset="utf-8">

With this line, hard-coded letters are displayed right, but values from the database are displayed wrong.

When I delete the line, I get the opposite: hard-coded is wrong, database values are right.

I'm confused, because the whole content is UTF-8 but it's displayed wrong on the PC, but it works on the Notebook. I guess the problem is server-side or I did something wrong at the exporting process.

I'd like to avoid the PHP functions utf8_encode() and utf8_decode().

Does anyone know a possible solution?

Make sure you set the charset of your PHP database connection object. This should be done before querying the database.

// tells the mysqli connection to deliver UTF-8 encoded strings.
$db = new mysqli($dbHost, $dbUser, $dbPassword, $dbName);
$db->set_charset('utf8');

// tells the pdo connection to deliver UTF-8 encoded strings.
$dsn = "mysql:host=$dbHost;dbname=$dbName;charset=utf8";
$db = new PDO($dsn, $dbUser, $dbPassword);

The examples above show how to set the charset for SQLI or PDO. Preparing the connection object this way, makes you independent of the database configuration, if necessary the connection will even convert the returned/sent data.

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