When you're doing an
INSERT query, you could be trying to insert a row containing a primary key that already exists in the table. Instead of doing a previous query to see if the key exists or not, you could try
ON DUPLICATE KEY UPDATE.
INSERT INTO table ( field1, field2 ) VALUES ( "foo", "bar" ) ON DUPLICATE KEY UPDATE field1="foo", field2="bar"