4

I've looked for similar questions with no success.

I have this piece of code:

form1.php

$query  = "INSERT INTO table1 ";
$query .= "(fname, lname, mail)";
$query .= " VALUES ";
$query .= "('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')"; 

$result = mysql_query($query) or die ("Query Failed: " . mysql_error());

And I want that the script will check if the value inserted exists in the corresponding column, and throw an error if it does. any ideas?

1
  • 1
    Note: If you use stored procedures instead of inline queries you can maintain your code well and also it will give you advantages like compiled queries, syntax checking, prevent sql injection etc.... Commented Dec 8, 2010 at 6:53

1 Answer 1

11

Create a UNIQUE key on the fields you care about, and detect the integrity error after the fact.

Sign up to request clarification or add additional context in comments.

2 Comments

This is really the only way, otherwise you end up with a race condition where failure goes unnoticed. If you check first and dump the record in if it's not already there, you're leaving open the possibility that someone could add the record in between your existence check and adding of the record.
Thanks Ignacio Vazquez-Abrams and AgentConundrum!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.