The cause of all UTIs is bacteria that enters the vagina and makes it way into the bloodstream through a number of ways. Sexual intercourse is the most common way for an infection to occur, but it is not the only way that infection occurs. Improper wiping after using the restroom is the second most common way for women to contract UTIs because they manually introduce the bacteria into their urinary tracts.
In the case of sexual intercourse, the pumping action can carry bacteria far into the vaginal opening where it can then easily enter the urinary tract. Urinating as soon as possible after sexual intercourse can reduce your chance of contracting an infection. When using the washroom, females always need to wipe front to back in order to avoid carrying bacteria into the vaginal folds where they can then enter the urinary tract.
In men, UTIs can be contracted, but it is much more difficult and almost always due to an abnormality that occurs in their anatomy.
In any case, it is not always immediately clear exactly how you might have contracted a UTI, but once it has been identified by a doctor there are treatments that can be started to relieve discomfort as soon as possible.