PDO ... SET NAMES UTF8危险吗?
在这里查看: http://www.php.net /manual/en/mysqlinfo.concepts.charset.php
我了解使用
设置名称utf8
SET NAMES utf8
不是一个好主意,但不清楚:
is not a good idea, but it is not clear:
- 出了什么问题?
- 如何避免呢?
- 实际上是在PHP 3.6或更高版本中为(或所有)PDO连接设置字符集的解决方案?
我担心代码很危险:
$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'
));
谢谢!
您是否真的还在使用PHP> = 3.6和<版本? 5.3.6?
Are you really still using PHP >= version 3.6 and < 5.3.6 ?
假设您拥有5.3.6或更高版本...
Assuming you have 5.3.6 or later...
字符集 和 PDO_MYSQL DSN 说你应该使用
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');
并且暗示(不够清楚)应该在适当的情况下用utf8mb4
替换utf8
.
And implies (not clearly enough) that utf8
should be replaced by utf8mb4
if appropriate.
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
效果不佳,但在5.3.6之前是替代品.
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
is not as good, but was the alternative before 5.3.6.
我认为危险"这个词太强了,甚至在5.3.6之前.
I think "dangerous" is too strong a word, even pre-5.3.6.
一种相关技术:在my.cnf
中使用init_command = SET NAMES ...
是不好的,因为当作为root
连接时不会执行init_command
.
A related technique: Using init_command = SET NAMES ...
in my.cnf
is bad because init_command
is not executed when connecting as root
.
utf8mb4
是首选的CHARACTER SET
,因为它包含表情符号和utf8
中缺少的一些中文字符.从MySQL版本5.5.3开始可以使用该字符集.
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.