PDO + MySQL and broken UTF-8 encoding

前端 未结 4 1015
孤独总比滥情好
孤独总比滥情好 2020-11-29 22:55

I use the PDO library with a MySQL database in PHP, but if I insert any data encoded in UTF-8, like Arabic words, it’s inserted into the database, but as ?????????

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 23:51

    You have to set the correct character set for the connection. Add the charset=utf8 option to the DSN (this is MySQL-specific!)

    $pdo = new PDO(
        'mysql:host=hostname;dbname=defaultDbName;charset=utf8',
        'username',
        'password'
    );
    

    However, in PHP versions before 5.3.6, you must use a workaround as the charset option is not supported.

    $pdo = new PDO(
        'mysql:host=hostname;dbname=defaultDbName',
        'username',
        'password',
        array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
    );
    

提交回复
热议问题