1
votes

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

1 Answers

27
votes

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.