问题
Looking at here: http://www.php.net/manual/en/mysqlinfo.concepts.charset.php
I understand that using
SET NAMES utf8
is not a good idea, but it is not clear:
- What is the issue?
- How to avoid it?
- Which is actually the solution to set the charset for a (or all) PDO connection(s) in a PHP 3.6 or higher?
The code I'm afraid is dangerous:
$this->_conn = new PDO('mysql:host=host.name.blabla;dbname=my_database_name','username', 'password',array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
));
Thanks!
回答1:
Are you really still using PHP >= version 3.6 and < 5.3.6 ?
Assuming you have 5.3.6 or later...
Character sets and PDO_MYSQL DSN say that you should use
$pdo = new PDO("mysql:host=localhost;dbname=mydb;charset=utf8",
'my_user', 'my_pass');
And implies (not clearly enough) that utf8
should be replaced by utf8mb4
if appropriate.
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
is not as good, but was the alternative before 5.3.6.
I think "dangerous" is too strong a word, even pre-5.3.6.
A related technique: Using init_command = SET NAMES ...
in my.cnf
is bad because init_command
is not executed when connecting as root
.
utf8mb4
is the preferred CHARACTER SET
for UTF-8 because it includes Emoji and some Chinese characters that were missing from utf8
. That charset is available starting with MySQL version 5.5.3.
来源:https://stackoverflow.com/questions/41782226/is-pdo-set-names-utf8-dangerous