I have been trying to implement a sort of IP blacklisting in PHP, where I store failed login attempts to a MySQL table with the following schema:
CREATE TABLE bl
The following query doesn't need run regularly and could be moved to a cron job:
DELETE FROM failures WHERE release_time < ?;
This "boolean" query will return 1 if the person is blacklisted, 0 otherwise:
SELECT
COUNT(ip_address) as blacklisted
FROM blacklist
WHERE
ip_address = ? AND
release_time > ? AND
failures > 5
It might speed things up as your not using PHP to count rows and compare numbers:
if ($row['blacklisted']) { /* ... */ }
I don't think you can avoid the last one really.