user892134
user892134

Reputation: 3214

Insert ignore/unique index

I am having trouble understanding how do this. commentid is an id of a row in the comment table. The vote table has three columns: id, commentid & username.

What i want is to insert into the vote table only if the last two columns(commentid and username) doesn't exist. $commentids is an array of multiple $id from the comment table. How do i add a unique index to accomplish this?

$commentids = explode(".",$id);

foreach($commentids as $value) {
  $insert = mysql_query("INSERT IGNORE INTO vote 
                           (id, commentid, username) 
                         VALUES 
                           ('','$value','$username')", $this->connect);
}

Upvotes: 1

Views: 1700

Answers (1)

mu is too short
mu is too short

Reputation: 434965

If you want the (commentid,username) pair to be unique then:

alter table vote add constraint unique (commentid, username);

If you want each of commentid and username to be globally unique within the table then:

alter table vote add constraint unique (commentid);
alter table vote add constraint unique (username);

Upvotes: 2

Related Questions