Inserting UTF-8 encoded string into UTF-8 encoded mysql table fails with “Incorrect string value”

后端 未结 4 1533
灰色年华
灰色年华 2020-12-01 15:17

Inserting UTF-8 encoded string into UTF-8 encoded table gives incorrect string value.

PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect str

相关标签:
4条回答
  • 2020-12-01 15:34

    to solve this issue, first you change your database field to utf8m4b charset. For example:

    ALTER TABLE `tb_name` CHANGE `field_name` `field_name` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL; 
    

    then in your db connection, set driver_options for it to utf8mb4. For example, if you use PDO

    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password');
    

    or in zend framework 1.2

    $dbParam = array('host' => 'localhost', 'username' => 'db_user_name',
                'password' => 'password', 'dbname' => 'db_name',
                'driver_options' => array(
                    '1002' => "SET NAMES 'utf8mb4'",
                    '12'    => 0 //this is not necessary
                )
            );
    
    0 讨论(0)
  • 2020-12-01 15:36

    I fixed the error: SQLSTATE[HY000]: General error: 1366 Incorrect string value ...... with this method:

    I use utf8mb4_unicode_ci for database Set utf8mb4_unicode_ci for all tables

    Set longblog datatype for column (not text, longtext.... you need big datatype to store 4 bytes of your content)

    It is okay now. If you use laravel, continue to edit config/database.php

    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    

    If you use function strtolower, replace it with mb_strtolower Notice: you have to put <meta charset="utf-8"> on your head tag

    0 讨论(0)
  • 2020-12-01 15:39

    0 讨论(0)
  • 2020-12-01 15:39

    In your PDO connecton, set the charset.

    new PDO('mysql:host=localhost;dbname=the_db;charset=utf8mb4', $user, $password);
    
    0 讨论(0)
提交回复
热议问题