-1

Some time ago I built a website using mysqli to access a database with user info. This database contains some text in cyrillic.

Yesteday I replaced the mysqli with PDO. Now all the cyrillic looks like this:

Ð’Ð¸ÐºÑ‚Ð¾Ñ€Ð¸Ñ Ð‘ÐµÐ»Ð¾Ñ‡ÐºÐ¸Ð½Ð°

I have UTF8 encoding everywhere. Here is my code:

$pdo = new PDO('mysql:host=mysql.host.com;dbname=db;charset=utf8', 
'database', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("set names utf8");
return $pdo;

and on the page

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

What could be the reason?

I googled a lot but couldn't find a solution.

Polina
  • 457
  • 1
  • 4
  • 8
  • Make sure the database is in utf-8 as well, this can help: https://stackoverflow.com/questions/1049728/how-do-i-see-what-character-set-a-mysql-database-table-column-is – Keloo Jul 30 '17 at 16:05
  • You might also be able to [try this](https://stackoverflow.com/a/45265242/7644018) with the PDO. – Paul T. Jul 30 '17 at 16:43
  • 1
    [Handling Unicode Front To Back In A Web App](http://kunststube.net/frontback/) – deceze Jul 31 '17 at 11:22
  • Wild guess: the data in your database is actually gibberish, because you have not set the correct charset in mysqli heretofore? – deceze Jul 31 '17 at 11:23
  • See "Mojibake" in http://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored – Rick James Aug 13 '17 at 17:37

1 Answers1

0

The last parameter of the PDO constructor call is the driver-specific options, given as an array with key => value pairs. The MySQL driver has a PDO::MYSQL_ATTR_INIT_COMMAND option where you can specify a command that is executed every time you connect to the database.

You can use the MySQL-specific query SET NAMES utf8 as a value for the init command, to tell MySQL to use UTF-8 as the character set for our connection:

$pdo = new PDO('mysql:host=mysql.host.com;dbname=db;array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"', 
'database', 'password');
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
pedram shabani
  • 1,654
  • 2
  • 20
  • 30