Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

mysql

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?

like image 574
Tom Granot Avatar asked Dec 21 '22 20:12

Tom Granot


1 Answers

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

like image 158
Ignacio Vazquez-Abrams Avatar answered Jan 13 '23 12:01

Ignacio Vazquez-Abrams