Page 1 of 1
Check for unique record before inserting.
Posted: Fri Jul 05, 2002 10:00 pm
by rayfusion
How do I check for a unqiue recording before trying to insert into a MySQL DB. I the record is already there, I want to throw back a message indicating so.
::rayfusion::
Posted: Sat Jul 06, 2002 12:20 am
by volka
You may define the fields as unique (single or combined).
If a duplicate is inserted mySQL will tell you. I.e.
Error: 1062 - Duplicate entry '1' for key 2
Posted: Sat Jul 06, 2002 5:27 am
by twigletmac
Code: Select all
<?php
$dbconn = mysql_connect($host, $user, $pass) or die(mysql_error());
mysql_select_db($db);
$sql = "SELECT field FROM table WHERE field='$input'";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
echo 'nope that's already in there';
} else {
// do what you want to do if the thing is unique
}
mysql_close();
?>
Volka's right about unique fields but you can also do something like the above to check for a duplicate entry and to take your own actions if one is found.
Mac