Hi
What is the best practice for checking if a record exists before inserting a new one?
Thanks in advance
Martin L
Checking if a record exists befor insert
Moderator: General Moderators
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
$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