An ear infection occurs when a bacterial or viral infection affects the middle ear — the sections of your ear just behind the eardrum. Ear infections can be painful because of inflammation and fluid buildup in the middle ear. Ear …