hello and welcome..Have you fell or banged your rib at all recently?
A bruised rib can give you spasms of pain when you either move or cough.
Sounds like you may also have a urine or kidney infection and would advise you take a sample to your doctor to have tested. If its kidney then you would also have discomfort around the waistline area but will feel it more in your back.
When i bruised a rib it was advised to sleep propped up with pillows to a sitting position as lying down was painful..take anti inflammatories and then keep till better..
Im not a doctor but would advise get checked out to make sure there are no under lying problems.