Is PDO … SET NAMES utf8 dangerous?

和自甴很熟 提交于 2019-12-11 04:28:27

问题


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:

  1. What is the issue?
  2. How to avoid it?
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!