Checking if a record exists befor insert

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
Martin L
Forum Newbie
Posts: 2
Joined: Wed Jul 10, 2002 3:49 pm

Checking if a record exists befor insert

Post by Martin L »

Hi

What is the best practice for checking if a record exists before inserting a new one?

Thanks in advance

Martin L
User avatar
mikeq
Forum Regular
Posts: 512
Joined: Fri May 03, 2002 3:33 am
Location: Edinburgh, Scotland

Post by mikeq »

One way is to code it into your application:

$Query = "select * from mytable where myfield='thevalue'";

$Result = MySQL_Query($Query);
$NumberRecords = MySQL_Num_Rows($Result);

if ($NumberRecords==0){
//no record exists do your insert
}
else{
//display error
}

Another way is to identify unique/primary keys on your table, when you try to insert a record that violates the unique/primary key then MySQL will generate an error, just capture that error and display a warning to the user.

Mike
Post Reply