I am trying to prevent the insertion of duplicate rows into mysql database. The table name is favorites and I have two columns in my table: company_id and user_id, I want to prevent users to try to add the same company to the db as a ‘favorite’ twice.
This is what I tried:
$query = "INSERT IGNORE INTO favorites (item_id, user_id) VALUES ( $item_id, $user_id )";
mysql_query($query,$conn);
But does not work.
I also tried to ‘alter table’ to add a primary key, however, I need both user_id and item_id to be keys, because the same favorited item can be favorited by more than one ‘user_id’ and the same ‘user_id’ can insert many different favorited items, so that data can be ‘duplicated’ but I am trying to prevent the exact same ‘user_id’ and ‘item_id’ to be inserted twice.
I appreciate any help with this.
You can use a composite primary key of the columns like so:
This means that same user_ids and item_ids are allowed and only a combination of them needs to be unique.