How to set charset for DB

Hello,

I have a question about the setting of charset (encoding) for DB. The fields in DB has correct UTF-8 General CI encoding but still non-latin characters are corrupted.
Please, let me know if it’s possible to set the charset somehow through the code?

Thank You.

If it’s MySQL, then you also need to set the client library encoding.
e.g.

 mysqli_set_charset('utf8');

or for PDO:

$handle = new PDO("mysql:host=localhost;dbname=dbname",
    'username', 'password', 
    [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"]);
2 Likes

Thank You! The 1st option works fine.

I am using PDO and tried second option but it is not working for me.
I get wired characters.

Please suggest me the correct way.

Hi @vivek

You you please try this code?

$host = 'localhost';
$dbname = 'test';
$username = 'root';
$password = '';
$charset = 'utf8';
$collate = 'utf8_unicode_ci';
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_PERSISTENT => false,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES $charset COLLATE $collate"
];

$pdo = new PDO($dsn, $username, $password, $options);

Hi @odan

No it’s still not working for me.
I have tried the same code which you have suggested.

I am getting "first_name": "ê¸°ìˆ ì„¸ë¯¸ë‚˜" instead of "first_name": "기술세미나" still.

Mayby try the new UTF-8 encoding of MySQL:

$charset = ‘utf8mb4’;
$collate = ‘utf8mb4_unicode_ci’;

Also check the DEFAULT CHARSET and COLLATE settings of your database, all tables and all varchar fields. Don’t use the browser and json_encode for debugging. Try xdebug. Store the resultset into a text file and check the encoding. Use var_dump or print_r instead of json_encode.