Ya, I think Specialmom has a good point. At this age an erect penis is not unusual just before peeing, so don't worry about that. You might want to record when you notice the leg stiffing and the time, etc. to look for a pattern. After eating etc.
Hopefully, this will just end on its own.
I don't think that is what is happening. I'd talk to the pediatrician about reflux and gas pains. A drop gas med when eating should prevent this.