Jump to content

A rather complicated task


php_nub_qq

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?

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.

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.

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.