0

I am having a problem with characters á, Á, ó, Ó, ú, Ú, í, Í, é, É being stored in our mysql DB as strange characters. We are using PDO for inserting to the DB.

The odd this is that I have a local copy of the site on my computer on WAMP which all works fine, and there is no encoding issue. The live site is on a Linux server, if that possibly makes a difference.

The local DB is a copy of the live DB, so all the encoding is the same in all of the tables.

I have tried setting the PDO encoding:

$pdo = new PDO('mysql:host=' . Settings::DBHostName() . ';charset=utf8;dbname=' . Settings::DBName(), Settings::DBUsername(), Settings::DBPassword(), array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));

Any other suggestions? I can't see why it would work locally and not on our live site?

DecoK
  • 135
  • 4
  • 12
  • 1
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8" seems to fix it. – DecoK Mar 14 '13 at 11:15
  • You want `utf8mb4`, nothing less, `SET NAMES utf8mb4` [**read all about why this is the way**](https://stackoverflow.com/questions/279170/utf-8-all-the-way-through) – Martin Jul 31 '17 at 15:32

2 Answers2

1

For the PHP versions since 5.3.6 you should set the encoding in DSN.
For all others to issue a conventional SET NAMES query is the only choice.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
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');
pedram shabani
  • 1,654
  • 2
  • 20
  • 30