For my employee’s table, an e-mail is a unique field. When I insert a new employee, I check on the existance of the email. If it already exists, you get an error message:
$selectquery ="SELECT * FROM employee WHERE empemail='$empemail'";
$selectresult=mysql_query($selectquery) or die("query fout " . mysql_error() );
if(mysql_num_rows($selectresult)==1)
{
$errormsgnewemployee = '<p id=notification>The email you entered already exists.</p>';
}
But how to do it when UPDATING a field? Because if I update an employees data (without changing his mail), it will not let me, because the email already exists. All I can think of it is to UPDATE first, check then if there are 2 records, if there are 2, update it back as it was before.
Is this a good approach or is there a better solution?
EDIT
My own solution is to UPDATE the table having a unique index on the table and using the query error:
if (mysql_error())
{
$errormsgnewemployee = '<p id=notification>Update failed. Please check if the email you entered already exists.</p>';
}
Because, why else would the user have error if it’s not for the only unique field? In all other cases the update would succeed.
You can use the same solution, you just need to “fetch this email address, but not mine” to check if there are any other users using it.
Eg. Before the update, do something like this:
SELECT 1 FROM employee WHERE empemail = '$empemail' AND id != '$myid';Should only return rows where the email belongs to someone else.
On a side note, there are potential security issues with interpolating variables into SQL queries like that – you shouldn’t do it. And the mysql_* functions are being deprecated should be replaced with PDO or mysqli alternatives.