Tom Granot
Tom Granot

Reputation: 1850

Check if value exists before inserting into MySQL DB in a PHP script

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?

Upvotes: 4

Views: 6071

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799300

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

Upvotes: 11

Related Questions