When you hold in a fart it builds gas up inside your stomach and when that gas builds up to a big enough point then the gas starts putting pain in your stomach.
When you need to fart to relieve that gas you should always do so and avoid holding in the fart because that is gas is needing expelled to keep your body healthy.
Holding in farts can also be harmful if done too much so excuse yourself to the bathroom if possible when in public and let the fart out.
Or if at home or outside then just let the fart out then as well because you'll feel much better and get that gas out of your stomach since the gas buildup in your stomach puts pressure on the inside of your stomach and intestines so that's why it causes pain.