Page 1 of 1

INSERT only if no value exists

Posted: Fri Dec 16, 2005 7:29 am
by waradmin
I have a form with just 1 button that puts in 2 values, Uname, pulled from a cookie, and friend_uname pulled from the address where index.php?user=usernamegoeshere

How do i check the DB for an existing value and if it exists not add the new information. But if there is no entry with those values, it puts it in. Thanks.

Posted: Fri Dec 16, 2005 7:34 am
by shiznatix
do a select on that id. get the number of rows returned. if it returned 1 or more rows then dont do anything, else insert.

Posted: Fri Dec 16, 2005 8:42 am
by timvw
Place a constraint on the column(s) that they have to be unique...

Posted: Fri Dec 16, 2005 11:17 am
by waradmin
Would the constraint work because each user can add eachother as a friend. Thus the Uname field can have unlimited entries as long as each one has a unique friend_uname and also friend_uname can appear unlimited times as long as it has a unique Uname with it.

I dont think i could do id's either because the ID field is auto_inc. Would there be a way to do it using the form inputs. Because the Add to Friends button is just a form with 2 hidden fields, is there a way to check the form values before submiting them. Like by doing a if $Uname == $row["Uname"] and $friend_uname == $row["friend_uname"] then exit else or something to that effect?

Posted: Fri Dec 16, 2005 1:46 pm
by timvw
The constraint should be on the combination of (user_id, friend_uname).

Posted: Fri Dec 16, 2005 4:44 pm
by waradmin
How would i set a constraint on the Uname and friend_uname? (note the table is layed out as id (auto inc) Uname (from cookie) and friend_uname (from page address template.php?user=_____)