As your child is having constipation
and passing hard stools, pain is due to passing hard stool by piercing rectal mucosa. You should make alterations in the diet of the child by giving dietary fibre rich food, fruits and vegetables and by giving plenty of oral fluids, water. Whenever he is having hard stools you can give oral laxatives like lactulose
to make hard stool soft. So consult your Pediatrician
to rule out any organic causes of constipation like hypothyroidism
and any strucutural large intestinal problems and regarding diet advise and management of constipation.