Database - handling of unique constraint violation

前端 未结 2 1398
無奈伤痛
無奈伤痛 2020-12-11 08:30

I have a user creation screen that takes various user details along with first name and mobile number. I have a corresponding USER table in which the First Name and the Mob

2条回答
  •  难免孤独
    2020-12-11 08:50

    Here's a PHP version of eggyal's answer, using MySQLi.

    // Error: 1062 SQLSTATE: 23000 (ER_DUP_ENTRY)               Message: Duplicate entry '%s' for key %d
    // Error: 1586 SQLSTATE: 23000 (ER_DUP_ENTRY_WITH_KEY_NAME) Message: Duplicate entry '%s' for key '%s'
    if($mysqli->errno === 1062 || $mysqli->errno === 1586)
    {
        if(preg_match("/Duplicate entry '(.*)' for key '(.*)'/", $mysqli->error, $matchArray) === 1)
        {
            $duplicatedValue = $matchArray[1];
            $uniqueKeyName = $matchArray[2];
    
            if(!($stmt = $mysqli->prepare('SELECT COLUMN_NAME'
                                        . '  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE'
                                        . ' WHERE CONSTRAINT_SCHEMA = ?'
                                        . '   AND CONSTRAINT_NAME = ?')))
            {
                die;    // Error? Check $mysqli->errno and $mysqli->error;
            }
            $schemaName = // Name of the schema (string).
            if(!$stmt->bind_param('ss', $schemaName, $uniqueKeyName))
            {
                die;    // Error? Check $mysqli->errno and $mysqli->error;
            }
            if(!$stmt->execute())
            {
                die;    // Error? Check $mysqli->errno and $mysqli->error;
            }
            $res = $stmt->get_result();
            if(!$res)
            {
                die;    // Error? Check $mysqli->errno and $mysqli->error;
            }
            $row = $res->fetch_assoc();
            if($row === null)
            {
                die;    // No results?
            }
            $columnName = $row['COLUMN_NAME'];
        }
    }
    

提交回复
热议问题