In The Name of Allaah, The Most Merciful, The Bestower of Mercy.
Imaam as Sa’di [rahimahullaah] said: The one entering the mosque should proceed with his right foot, and then says:
بسم الله، والسلام على رسول الله، اللهم اغفر لي ذنوبي وافتح لي أبواب رحمتك
[Bismillaahi Allaahumma Salli-Wa-Sallim Alaa Muhammad; Allaahumma Ighfir-lee Dzo-noo-bee, Waf-tah-lee Abwaaba Rahmatika – In the Name of Allaah, and may peace and blessings be upon the Messenger of Allaah. O Allaah! Forgive me my sins and open the doors of mercy for me] [Reported by Muslim, No:713]
Then he should pre-occupy himself with Prayer, Remembrance of Allaah, Recitation of the Qur’aan and Knowledge. He either teaches or learns, or listens. He gives advice to those in the mosque and directs them to that which contains good. And he does not pre-occupy himself with other than that, being engrossed in the affairs of the dunyaah, for the Mosques have not been built, except for seeking nearness to Allaah, whilst the other places are for exploring and pre-occupation with the (affairs) of the Dunyaah. [Source: Noorul Basaa-ir Wal Albaab. Page: 72]
When leaving the Masjid
بسم الله والصلاة والسلام على رسول الله
اللَّهُمَّ إِنِّي أَسْأَلُكَ مِنْ فَضْلِكَ
In the Name of Allaah, and may peace and blessings be upon the Messenger of Allaah. O Allaah! I ask You for Your Bounty.
Regarding the statement [اللَّهُمَّ افْتَحْ لِي أَبْوَابَ رَحْمَتِكَ – O Allaah open for me the doors of mercy], it is said (i.e. by the scholars) that perhaps the wisdom behind this is because entry into the masjid is connected to seeking after the afterlife and mercy is a specific thing pursued in relation to the afterlife. And exiting the Masjid is connected to seeking after livelihood in worldly life and this is what is intended by the word [فضل – Bounty], which the statement of Allaah [The Most High] indicates to (in Surah Al-Jumu’ah) as follows: [فَإِذَا قُضِيَتِ الصَّلَاةُ فَانْتَشِرُوا فِي الْأَرْضِ وَابْتَغُوا مِنْ فَضْلِ اللَّهِ – Then when the (Jumu’ah) Salat (prayer) is finished, you may disperse through the land, and seek the Bounty of Allah (by working, etc.) [62:10]
It is said (i.e. by the scholars) that the one who enters the Masjid busies himself by doing what will draw him close to Allaah, earns him Allaah’s reward and Paradise; therefore the mention of ‘Mercy’ is suitable in this instance (i.e. the mention of mercy in the supplication when entering the masjid). And when he exits the Masjid, he goes about in the earth to seek after the bounty of Allaah – good and lawful provision; so the mention of [الفضل- Bounty] is suitable in this instance. And Allaah knows best. [Source: Fiqhul Ad’iyah Wal Adhkaar’ page 124′ parts 3&4. By Shaikh Abdur-Razzaaq Al-Badr]