prefix . 'loyaltypress_rate_limits'; $now = time(); $key = substr( $key, 0, 100 ); // Atomic upsert: reset the window if it has elapsed, otherwise increment. // phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->query( $wpdb->prepare( 'INSERT INTO %i (rl_key, hits, window_start) VALUES (%s, 1, %d) ON DUPLICATE KEY UPDATE hits = IF(window_start + %d <= %d, 1, hits + 1), window_start = IF(window_start + %d <= %d, %d, window_start)', $table, $key, $now, $window, $now, $window, $now, $now ) ); $hits = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT hits FROM %i WHERE rl_key = %s', $table, $key ) ); // phpcs:enable return $hits <= $max; } }