Name of duplicated field

Just curious… If there is ‘duplicated entry’ error (code 1062) in MYSQL, is that possible to find in PDO or directly in database name of duplicated field without to parse error message?

you’re going to want to see the entire error message

it tells you the dupllcated value, and it tells you the duplicated key name (sometimes it’s the primary key, sometimes it’s a different unique key)

I know. But if to do with error message that means something like strpos($message, $key) !== false.

My question is: whether this key saved somewhere in DB, just to get it with last_duplicated_key() or something like that?

I had help with this a long time ago and I commented it so that I wouldn’t forget.


            /*
             * echo "unique index" . $e->errorInfo[1] . "<br>";
             *
             * An error has occurred if the error number is for something that
             * this code is designed to handle, i.e. a duplicate index, handle it
             * by telling the user what was wrong with the data they submitted
             * failure due to a specific error number that can be recovered
             * from by the visitor submitting a different value
             *
             * return false;
             *
             * else the error is for something else, either due to a
             * programming mistake or not validating input data properly,
             * that the visitor cannot do anything about or needs to know about
             *
             * throw $e;
             *
             * re-throw the exception and let the next higher exception
             * handler, php in this case, catch and handle it
             */

            if ($e->errorInfo[1] === 1062) {
                return false;
            }

no, you have to inspect the row of data you were trying to insert

one of the values already exists in the table, in a column which doesn’t allow duplicates

No, I wouldn’t and I have not recommend it never.

Look… Yet I should to do something like…

try {
    $db->insert();
} catch (DBExecuteException $exception) {
    if ($exception->getCode() == 1062 
              && strpos($exception->getMessage(), 'LoginIndex') !== false) {
        //handle exception
    }
}

But I would like to have…

$db->insert();
if ($db->getLastDuplicatedKey() == 'LoginIndex') {
    //handle exception
}

…of course if this possible at all.

i have no idea

perhaps you can ask the moderators to move this question to the php forum

i can tell you only about the database side of it

moved to PHP forum

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.