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

后端 未结 4 1549
灰色年华
灰色年华 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
                )
            );
    

提交回复
热议问题