0

I'm trying the following code over Lubuntu 12.04, Apache, PHP 5.5.3-1ubuntu2, pdo_mysql 5.5.32 and MySQL 5.5.32-0ubuntu7-log.

$dbh = new \PDO("mysql:host=$hostname;dbname=test_db;charset=utf-8", $username, $password);

$dbh->exec('SET NAMES utf8');

$sql = "SELECT name FROM test_table";
foreach ($dbh->query($sql) as $row) {
    error_log(bin2hex($row['name']));
}

And I get 44656d6f737472616369c3b36e. If I comment the SET NAMES utf8 query, I get 44656d6f737472616369f36e (the difference being c3b3 instead of f3).

From the MySQL client, When issuing SELECT HEX(name) FROM test_table limit 1; I get 44656D6F737472616369C3B36E.

So it seems the extra query is needed, but according to this it shouldn't.

Am I doing something wrong?

EDIT

I tried both with charset=utf-8 and charset=utf8 and I'm getting the same result.

Output of SHOW CREATE TABLE test_table:

CREATE TABLE `test_table` (
    `name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Relevant output of SHOW FULL COLUMNS FROM test_table:

+-------+--------------+-----------------+
| Field | Type         | Collation       |
+-------+--------------+-----------------+
| name  | varchar(255) | utf8_general_ci |
+-------+--------------+-----------------+
Community
  • 1
  • 1
hectorh30
  • 763
  • 1
  • 6
  • 12

1 Answers1

1

You'll have it in your connection string like:

"mysql:host=$host;dbname=$db;charset=utf8"

HOWEVER, prior to PHP 5.3.6, the charset option was ignored. If you're running an older version of PHP, you must do it like this:

$dbh = new PDO("mysql:$connstr",  $user, $password);
$dbh->exec("set names utf8");

Reference: PHP PDO: charset, set names?

Or if you want you can do this:

<?php

$dsn = 'mysql:host=localhost;dbname=testdb';

$username = 'username';
$password = 'password';

$options = array(
  PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
); 

$dbh = new PDO($dsn, $username, $password, $options);
Dharman
  • 30,962
  • 25
  • 85
  • 135