SQLSTATE[HY000]: General error: 3988 Conversion from collation utf8mb3_general_ci into utf8mb4_general_ci impossible for parameter

Issue

I am doing a registration form and it gives me this error : Uncaught PDOException: SQLSTATE[HY000]: General error: 3988 Conversion from collation utf8mb3_general_ci into utf8mb4_general_ci impossible for parameter; every first time i register in, then it does what it is supposed to do. The error started when I inserted the value status in the database. the bug seems to be non-persistent and sometimes it continues the code execution despite the given fatal error. pls help

CREATE TABLE `users` (
    `id` varchar(30) NOT NULL,
    `username` varchar(50) NOT NULL,
    `password` varchar(255) NOT NULL,
    `status` varchar(50) NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
<?php

$db_config = $config['db_engine'] . ":host=".$config['db_host'] . ";dbname=" . $config['db_name'].";charset=utf8mb4";

try {
    $pdo = new PDO($db_config, $config['db_user'], $config['db_password'], [
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
    ]);

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
    exit("Impossibile connettersi al database: " . $e->getMessage());
}
?>
$query = "
                INSERT INTO users
                VALUES (:id, :username, :password, :status)
            ";
            $status = "Active now";
            $check = $pdo->prepare($query);
            $check->bindParam(':id', $randomID, PDO::PARAM_STR);
            $check->bindParam(':username', $username, PDO::PARAM_STR);
            $check->bindParam(':password', $password_hash, PDO::PARAM_STR);
            $check->bindParam(':status', $status, PDO::PARAM_STR);
            $check->execute();

            if ($check->rowCount() > 0) {
                $msg = 'Registrazione eseguita con successo';
            } else {
                $msg = 'Problemi con l\'inserimento dei dati';
            }

Solution

at the end i resolved like this

$db_config = $config['db_engine'] . ":host=".$config['db_host'] . ";dbname=" . $config['db_name'].";charset=utf8mb4";

try {
    $pdo = new PDO($db_config, $config['db_user'], $config['db_password'], [
        PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4 COLLATE utf8mb4_general_ci"
    ]);

    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

} catch (PDOException $e) {
    exit("Impossibile connettersi al database: " . $e->getMessage());
}

Answered By – Leonardo Rosati

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published