How to Handle Error for Duplicate Entries

How to handle error for duplicate entries?

To check for this specific error, you need to find the error code. It is 1062 for duplicate key. Then use the result from errno() to compare with:

mysqli_query('INSERT INTO ...');
if (mysqli_errno() == 1062) {
print 'no way!';
}

A note on programming style
You should always seek to avoid the use of magic numbers (I know, I was the one to introduce it in this answer). Instead, you could assign the known error code (1062) to a constant (e.g. MYSQLI_CODE_DUPLICATE_KEY). This will make your code easier to maintain as the condition in the if statement is still readable in a few months when the meaning of 1062 has faded from memory :)

Catch duplicate entry Exception

I use spring so we resolve it by org.springframework.dao.DataIntegrityViolationException

try {
ao_history_repository.save(new AoHistory(..));
} catch (DataIntegrityViolationException e) {
System.out.println("history already exist");
}

But as @KevinGuancheDarias mention it:

Please note that while this works. I suggest to solve the problem by
issuing a findBy before the save
, as this is messy, and I think it's
not warranted that it will work in future versions, may even break
without notification.

How to handle QueryException for duplicate entries in Laravel

I was very near to my answer, it was all about namespace issue and error display issue:

Illuminate\Database\QueryException $e should be:
\Illuminate\Database\QueryException $e

        try {
DB::table('users')->insert($userData);
} catch(\Illuminate\Database\QueryException $e){
$errorCode = $e->errorInfo[1];
if($errorCode == '1062'){
dd('Duplicate Entry');
}
}

return and throw for error did not work, but 'dd' method worked. So this saves my time in querying twice to identify the duplicates and insert and am happy for it :)

How to handle duplicate entry for email error?

you can check like this way.

public function store(StoreUserInfo $data)
{
$data->validated();

$email = User::where('email',$data['email'])->first();
if($email){
return redirect()
->route('admin.users')
->with('message', 'Email is already exists.');
}

$user = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'city' => $data['city']
]);

return redirect()
->route('admin.users')
->with('message', 'User created successfully');
}

How to format a mysql duplicate entry error?

I actually came up with a decent solution.

Because the sqlMessage will always be in the same format, I first split the sqlMessage into an array, and then extracted the value entered, and then I also extracted the field, but since the field is in a format "database.field_UNIQUE", I had to extract the field that is in between the "." and "_" characters.

The code looks like this:

if (err.errno === 1062) {
const errWords = err.sqlMessage.split(" ");
const entry = errWords[2];
const fieldDB = errWords[5];
const formattedField = fieldDB.substring(fieldDB.lastIndexOf(".") + 1, fieldDB.lastIndexOf("_"));
console.log( `Duplicate entry - ${formattedField}: ${entry}`)
return res.status(400).json({ error: `Duplicate entry - ${formattedField}: ${entry}` });
}

The result will be:

Duplicate entry - username: 'todd'

Should check for duplicate or catch exception from database?

For you to check client side(in your program) if there is a duplicate key, it would require querying the database. Since the insert query will return an error if there is already a record existing with the same PK, it is not necessary to perform this check before the insert statement is sent.

You can insert, catch the exception/error code (i'm not sure if it will give an exception in java, or return an error code) and then alert the user.

EDIT -

If there are many users using the same database, the main issue if you check and then insert will be that someone else can insert the same key after you checked but before you insert. IF you would like to do it this way, you would need to use transactions - the check and insert must both happen in the same transaction. You can read up on MySQL transactions here.

Symfony error handling duplicate entry

Does this data come from a form? If so, maybe you could check out http://symfony.com/doc/current/reference/constraints/UniqueEntity.html. This adds a unique validation based on fields you provide. If you don't use a form you could still use the validator separately to validate your object.



Related Topics



Leave a reply



Submit