1

i am using PDO for connecting to MYSQL database

all tables in database have utf8_unicode_ci Collation

here is my connection code :

<?php
$mysql_username = "root";
$mysql_password = "";
$mysql_host = "localhost";
$mysql_database = "cms";

try
{
    //connect
    global $db;
    $db = new PDO('mysql:dbname=' . $mysql_database . ';host=' . $mysql_host . ';charset=utf8;', $mysql_username, $mysql_password);
    $db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex)
{
    die("Unable Connect To DataBase");
}
?>

in localhost i have no problem with encoding but when i uploaded the source to a host i see ?????? instead of characters?

1 Answer 1

27

This:

$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, 'SET NAMES utf8');

is entirely pointless. See http://php.net/manual/en/ref.pdo-mysql.php. The MYSQL_ATTR_INIT_COMMAND is executed right after the connection is established, no later. If you set this on an already fully created PDO object, it's too late and it never executes. You need to pass it to the constructor:

new PDO(..., ..., ..., array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'))

Alternatively, if your PHP version supports it, add charset=utf8 to the DSN.

Sign up to request clarification or add additional context in comments.

5 Comments

i did that but still no effect
Is everything else properly set up? See stackoverflow.com/questions/279170/utf-8-all-the-way-through
Worked great on CentOS 6, MySQL 5.1. Saved me some lookup time, thanks! IMHO this should be accepted as the correct answer, I had the same ??????? for Kanji, did this, worked. Done.
It worked! This method removes my error on Apache/2.2.15 (CentOS), Mysql 5.5.54. Really, thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.