Why your ears hurt when flying
It’s a pressure differential. When the air pressure changes dramatically on one side of the eardrum and not the other the eardrum stretches. This muffles your hearing, and eventually causing excruciating pain.
As has been pointed out, if the eardrum ruptures you frequently get relief. This is because the act of rupture allows the pressure to equalize on both sides. If there is infection, it may also allow pus and sundry to drain out of the ear, likewise relieving pressure. It also can mess with your hearing.
What you should do about painful ears while flying
Well there are are several options here.
Everybody has problems sometimes - usually in connection with cold, head congestion, allergy or the like. If it’s a transitory problem - i.e. you’re sick or have seasonal allergies - either don’t fly while suffering from the condition, or ask for some high-power decongestants/painkillers. The valsalva manuver has its uses, but can also precipitate a rupture if you’re in dire straits.
If you frequently have problems see a doctor - you may have a chronic infection of some sort, or unusually small eustachian tubes, or something else going on. There are medications for many of these conditions and if you aren’t a pilot I’d encourage you to use them.
If you always have problems see an ear-nose-throat guy and be very explicit about the problem, the pain level, and your need to fly. In some extreme cases, steroids to reduce inflammation or even surgery may be indicated, but the less extreme methods will be tried first.
If your eardrums rupture
See a doctor. It’s an indication Something Is Wrong. It may be a temporary thing requiring no intervention, just time, but if it’s not you’ll want to take care of it so you don’t wind up with chronic problems. I work with a gal who let things go a bit too long - now, she just about screams riding an elevator up and down more than about 5 floors. And she lives and works in downtown Chicago, where we have buildings up to 110 stories tall. This is not pretty.