PDO connection: UTF-8 declaration with SET NAMES / CHARACTER SET?

According to php.net, StackOverflow and other sources of trust, I can find 4 different ways to install UTF-8 in a PDO connection, but I can not find which one is better to choose.

PDO connection code (and some inits):

$localhost = $_SERVER['SERVER_NAME'] == 'localhost'; error_reporting(-1); ini_set('display_errors', $localhost); // Old : error_reporting($localhost ? -1 : 0); see answer above date_default_timezone_set('Europe/Paris'); $pdo_db = 'mysql:host=localhost;dbname=local_db;charset=utf8'; // METHOD #1 $pdo_login = 'root'; $pdo_pass = 'localpass'; try { $db = new PDO($pdo_db, $pdo_login, $pdo_pass, array( PDO::ATTR_ERRMODE => $localhost ? PDO::ERRMODE_EXCEPTION : PDO::ERRMODE_SILENT, PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', // METHOD #2 )); $db -> exec('SET NAMES utf8'); // METHOD #3 $db -> exec('SET CHARACTER SET utf8'); // METHOD #4 $db -> exec('SET time_zone = \''.date_default_timezone_get().'\''); } catch (PDOException $error) { die($error -> getMessage()); } 

So, I realized that method 1 only works with PHP 5.3+ (but it seems to be a little buggy), and method 2 only for MySQL. The differences between MySQL methods 3 and 4 are a thing , but I still don't know which one is better. And is there a way to call SET NAMES in PDO attributes, but not just for MySQL?

Thanks!

+8
php pdo database-connection
source share
2 answers

Installation in DSN is correct (although it is supported only with 5.3).
You can use this and SET NAMES at the same time.

All other methods will make possible the infamous injection of GBK.

Please note that your setting for error_reporting () is completely incorrect. it must be -1 unconditional. If you are concerned about displaying errors, there is a proper ini setting for this called display_errors , which can be set at runtime.
While error_reporting sets the error level and should be maximum all the time.

+6
source share

I always write the following code in my dbconfig file:

 mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'"); 
-2
source share

All Articles