1

I have a large array. Is there an alternate method to check if $value in the array is present in the MySql table vote and if not then insert $value into vote. This is what i am doing currently. Is there a better method?

foreach($rowids as $value) {


        $select = mysql_query("SELECT voteid FROM vote WHERE username='$username' AND voteid='$value' LIMIT 1",$this->connect);

            if(mysql_num_rows($select)==0) {

        $insert = mysql_query("INSERT INTO vote VALUES ('','$value','$username')",$this->connect);

            }
        }
2
  • You could simply attempt the insert and handle the error, assuming the appropriate unique constraints are in place
    – Phil
    Oct 14, 2011 at 1:24
  • in most cases you would want to store a userid, instead of a varchar username.
    – carpii
    Oct 14, 2011 at 1:33

1 Answer 1

4

If you put a UNIQUE INDEX on (value,username) then you could use INSERT IGNORE:

INSERT IGNORE INTO vote (foo,voteid,username) VALUES ('','$value','$username')

To add a UNIQUE INDEX:

ALTER TABLE vote ADD UNIQUE INDEX idx (voteid,username)

This will fail if there are "duplicate" rows in vote that violate the UNIQUE INDEX. To drop duplicate rows and add the UNIQUE INDEX at the same time:

ALTER IGNORE TABLE vote ADD UNIQUE INDEX idx (voteid,username)
2
  • thanks..is this a better method performance wise for hundreds of users?
    – user892134
    Oct 14, 2011 at 1:38
  • I think this must be better than issuing 2 queries + equivalent logic in PHP. Moreover, a few hundred inserts should pose no problem at all for any database.
    – unutbu
    Oct 14, 2011 at 1:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.