INSERT only if no value exists

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
waradmin
Forum Contributor
Posts: 240
Joined: Fri Nov 04, 2005 2:57 pm

INSERT only if no value exists

Post 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.
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post 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.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Place a constraint on the column(s) that they have to be unique...
User avatar
waradmin
Forum Contributor
Posts: 240
Joined: Fri Nov 04, 2005 2:57 pm

Post 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?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

The constraint should be on the combination of (user_id, friend_uname).
User avatar
waradmin
Forum Contributor
Posts: 240
Joined: Fri Nov 04, 2005 2:57 pm

Post 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=_____)
Post Reply