UTF-8 Database Problem

前端 未结 3 502
终归单人心
终归单人心 2020-12-21 05:30

I\'ve a MySQL table that has a UTF-8 charset and upon attempting to insert to it via a PHP form, the database gives the following error:

PDOStatement:

相关标签:
3条回答
  • 2020-12-21 06:23

    Your database might be set to UTF-8, but the database connection also needs to be set to UTF-8. You should do that with a SET NAMES utf8 statement. You can use the driver_options in PDO to have it execute that as soon as you connect:

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

    Have a look at the following two links for more detailed information about making sure your entire site uses UTF-8 appropriately:

    • UTF-8 all the way through…
    • UTF8, PHP and MySQL
    0 讨论(0)
  • 2020-12-21 06:26

    E8 is greater than the maximum usable character 7F in a one-byte UTF8 character: http://en.wikipedia.org/wiki/UTF-8

    It seems your connection is not set to UTF8 but some other 8 bit encoding like ISO Latin. If you set the database to UTF8 you only change the character set the database uses internally, connections may be on a different default value (latin1 for older MySQL versions) so you should try to send an initial SET CHARACTER SET utf-8 after connecting to the database. If you have access to my.cnf you can also set the correct default value there, but keep in mind that changing the default may break any other sites/apps running on the same host.

    0 讨论(0)
  • 2020-12-21 06:26

    Before passing the value to Mysql you can use the following code:

    $val = mb_check_encoding($val, 'UTF-8') ? $val : utf8_encode($val);

    convert the string the to UTF-8, If it's matter of only one field.

    0 讨论(0)
提交回复
热议问题