TMNuclear
TMNuclear

Reputation: 1175

PHP MYSQL How to check if record already exists when UPDATING?

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.

Upvotes: 1

Views: 5681

Answers (2)

Eugene Manuilov
Eugene Manuilov

Reputation: 4361

I would recommend you to use INSERT ... ON DUPLICATE UPDATE ... sql construction. Take a deeper look at manual.

So your query could be the following:

INSERT INTO employee (email, first_name, last_name, ...) 
VALUES ('[email protected]', 'nik', 'smtih', ...) 
ON DUPLICATE UPDATE 
    first_name = 'nik', 
    last_name = 'smith', 
    ...

Pay attention that INSERT part of this query will fail due to UNIQUE KEY constraint, that is why the second part of the query, ON DUPLICATE UPDATE, will be executed and the data will be updated instead of inserting.

Upvotes: 4

Brenton Alker
Brenton Alker

Reputation: 9072

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.

Upvotes: 4

Related Questions