Check for unique record before inserting.

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
rayfusion
Forum Newbie
Posts: 3
Joined: Fri Jul 05, 2002 10:00 pm

Check for unique record before inserting.

Post 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::
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post 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) &#123;
    echo 'nope that's already in there';
&#125; else &#123;
    // do what you want to do if the thing is unique
&#125;
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
Post Reply