PHP PDO: charset, set names?

前端 未结 9 909
孤独总比滥情好
孤独总比滥情好 2020-11-22 06:49

I had this previously in my normal mysql_* connection:

mysql_set_charset(\"utf8\",$link);
mysql_query(\"SET NAMES \'UTF8\'\");

Do I need it

9条回答
  •  猫巷女王i
    2020-11-22 07:01

    For completeness, there're actually three ways to set the encoding when connecting to MySQL from PDO and which ones are available depend on your PHP version. The order of preference would be:

    1. charset parameter in the DSN string
    2. Run SET NAMES utf8 with PDO::MYSQL_ATTR_INIT_COMMAND connection option
    3. Run SET NAMES utf8 manually

    This sample code implements all three:

     PDO::ERRMODE_EXCEPTION,
    );
    
    if( version_compare(PHP_VERSION, '5.3.6', '<') ){
        if( defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
            $options[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES ' . DB_ENCODING;
        }
    }else{
        $dsn .= ';charset=' . DB_ENCODING;
    }
    
    $conn = @new PDO($dsn, DB_USER, DB_PASSWORD, $options);
    
    if( version_compare(PHP_VERSION, '5.3.6', '<') && !defined('PDO::MYSQL_ATTR_INIT_COMMAND') ){
        $sql = 'SET NAMES ' . DB_ENCODING;
        $conn->exec($sql);
    }
    

    Doing all three is probably overkill (unless you're writing a class you plan to distribute or reuse).

提交回复
热议问题