If you really want to write your own (working) request ..
INSERT INTO groupdentlink ( f_dent_id, f_group_id, f_schedule_id ) SELECT '$_POST[id]' f_dent_id, '$groupid' f_group_id, '$scheduleid' f_schedule_id FROM DUAL WHERE NOT EXISTS ( SELECT 1 FROM `groupdentlink` WHERE f_dent_id = '$_POST[id]' AND f_group_id = '$groupid' LIMIT 1
... but MySQL can handle all this for you!
You do not need primary keys to force MySQL to handle this for you; you must add a UNIQUE
key UNIQUE
for the combined set of two columns.
A request to add a unique dent_group_uniq_key
to groupdentlink
.
ALTER TABLE groupdentlink ADD UNIQUE KEY `dent_group_uniq_key` ( f_dent_id, f_group_id );
Then use INSERT IGNORE
for your query:
INSERT IGNORE INTO groupdentlink ( f_dent_id, f_group_id, f_schedule_id ) VALUES ( '$_POST[id]', '$groupid', '$scheduleid' )
INSERT IGNORE
will try to insert a row into your table; if it fails due to a key constraint, it will act as if nothing was happening.
Filip RosΓ©en - refp
source share