I have two unique indexes set on my users table columns (email, username) but when I try to register a new user with a taken email AND taken username, it displays an exception as expected. However, it just shows an exception on the email column, not the username:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'martynbissett@yahoo.co.uk' for key 'email_2'
In my code I've tried doing something like this:
try {
// attempt to save
} catch(\Exception $e) {
switch($e->getCode()) {
case 23000:
$this->flash->error('Email(?) address already taken'); // or is it username?
break;
default:
$this->flash->error($e->getMessage());
}
}
Also, you can see I want to present a nicer error message than SQLSTATE[23000]: Integrity const... so I'm catching the error code. But I don't know in any given case which column is the problem ("Email address taken" or "Username taken"?)
Do I need to perform separate queries for each of these prior during validation? If I just had one unique index (e.g. only email) then I could just rely on the code in the exception, but if I have two....
Just do the validation before inserting to database. Queries to check if specified value exists are really cheap, so don't be afraid.
Database constraints will be additional protection.