Jump to content

A rather complicated task


Go to solution Solved by Psycho,

Recommended Posts

Good day fellow programmers.

 

I need to alter the following table:

CREATE TABLE `friendships` (
 `sender` int(11) NOT NULL,
 `recipient` int(11) NOT NULL,
) 

so that sender and recipient cannot be the same person ( same ID ) neither can they repeat no matter who is who. I suppose you didn't understand me so I best give an example:

sender	recipient
1	2        << OK
2	1        << NOT OK - record already exists in opposite order
1	3        << OK
1	5        << OK
2	3        << OK
2	5        << OK
3	3        << NOT OK - same ID

I find it hard to believe that it is achievable without the contribution of great PHP but I thought I should ask before proceeding. Anyone?

Edited by php_nub_qq
Link to comment
https://forums.phpfreaks.com/topic/276595-a-rather-complicated-task/
Share on other sites

What do you mean by "alter" the table? Are you wanting to modify records already in the table, are you wanting to modify the table schema to prevent those conditions (don't think it's possible)  or are you wanting to create code to prevent those "error" conditions. Both are very easy.

Edited by Psycho

You should have a function for getting and setting friendships, so the code would only have to be in one place.

If you do it in mysql (which you can't anyway, not possible), your insert would fail, giving you LESS information than your few conditionals will.

  • Solution

You can put a unique constraint on a combination between multiple fields. So, you would not be able to enter two records which have the same value for sender and the same value for recipient. But, there is no way I know of through the DB schema to prevent two records where the values are swapped between the fields in the two records (e.g. same as the second record in your example).

 

Why not do a simple SELECT before inserting the reocrd? No need for a bunch of if()'s in your code.

I can think of some more complicated solutions, such as creating a trigger that creates a unique value based upon the two IDs and sets that value in a third field with a unique constraint. But, really that is overkill.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.