All perfect praise be to Allaah, The Lord of the Worlds. I testify that there is none worthy of worship except Allaah, and that Muhammad, sallallaahu ‘alayhi wa sallam, is His Slave and Messenger.
Having an erection while praying or outside it is something beyond one’s control. However, if it is induced by thought, imagination or fighting the urge to urinate, then it causes one to be committing something disliked, since it contradicts the state of full submissiveness , which is the essence of prayer.
According to jurists, it is recommended to be fully submissive while praying and reflect on what is recited in prayer, on its Athkaar (mention of Allaah) and everything pertaining to it. It is also recommended to refrain from thinking of anything that is not related to prayer. If this happens, it does not invalidate the prayer, though it is disliked whether he is thinking of something lawful or unlawful.
On the other hand, if one has an erection during the prayer for no reason, then we hope that there is nothing disliked in his prayer. For further information, please refer to Fatwa 91469.
Allaah Knows best.