Language:
كتاب العمل فى الصلاة
21  
Actions while Praying
(18)
Chapter: Thinking of something during As-Salat (the prayer)
(18)
باب تَفَكُّرِ الرَّجُلِ الشَّىْءَ فِي الصَّلاَةِ
Sahih al-Bukhari 1222

Narrated Abu Huraira:

Allah's Messenger (ﷺ) said, "When the Adhan for the prayer is pronounced, then Satan takes to his heels passing wind so that he may not hear the Adhan and when the Mu'adh-dhin finishes, he comes back; and when the Iqama is pronounced he again takes to his heels and when it is finished, he again comes back and continues reminding the praying person of things that he used not to remember when not in prayer till he forgets how much he has prayed." Abu Salama bin `Abdur-Rahman said, "If anyone of you has such a thing (forgetting the number of rak`at he has prayed) he should perform two prostrations of Sahu (i.e. forgetfulness) while sitting." Abu Salama narrates this from Abu Huraira.

حَدَّثَنَا يَحْيَى بْنُ بُكَيْرٍ، حَدَّثَنَا اللَّيْثُ، عَنْ جَعْفَرٍ، عَنِ الأَعْرَجِ، قَالَ قَالَ أَبُو هُرَيْرَةَ ـ رضى الله عنه ـ قَالَ رَسُولُ اللَّهِ صلى الله عليه وسلم ‏ "‏ إِذَا أُذِّنَ بِالصَّلاَةِ أَدْبَرَ الشَّيْطَانُ لَهُ ضُرَاطٌ حَتَّى لاَ يَسْمَعَ التَّأْذِينَ، فَإِذَا سَكَتَ الْمُؤَذِّنُ أَقْبَلَ، فَإِذَا ثُوِّبَ أَدْبَرَ فَإِذَا سَكَتَ أَقْبَلَ، فَلاَ يَزَالُ بِالْمَرْءِ يَقُولُ لَهُ اذْكُرْ مَا لَمْ يَكُنْ يَذْكُرُ حَتَّى لاَ يَدْرِي كَمْ صَلَّى ‏"‏‏.‏ قَالَ أَبُو سَلَمَةَ بْنُ عَبْدِ الرَّحْمَنِ إِذَا فَعَلَ أَحَدُكُمْ ذَلِكَ فَلْيَسْجُدْ سَجْدَتَيْنِ وَهُوَ قَاعِدٌ‏.‏ وَسَمِعَهُ أَبُو سَلَمَةَ مِنْ أَبِي هُرَيْرَةَ ـ رضى الله عنه‏.‏
Reference : Sahih al-Bukhari 1222
In-book reference : Book 21, Hadith 26
USC-MSA web (English) reference : Vol. 2, Book 22, Hadith 313
  (deprecated numbering scheme)