For `Unique Impression IP` as there is no need for a autoincrement primary key, use `VARBINARY(16)` for IP address, and as the primary key. Use [INET6_ATON()](https://dev.mysql.com/doc/refman/5.6/en/miscellaneous-functions.html#function_inet6-aton) when inserting it to keep it in a compact form. Use: INSERT IGNORE INTO `Unique Impression IP` VALUES (INET6_ATON($var)) And look at rows affected to see if that exists or not for your `UPDATE Banner` statement branch. As it's a unique key (primary keys are unique) it will only be inserted once. This removes a race condition in your current code.