Can I buy an Iphone 5 online and put it on a contract with a phone company?

I don't know anything about contracts or phone companies, but would I be able to purchase an IPhone 5 from apple.com and go to a phone company and get a contract for it? I have T Mobile. The reason I don't want to buy it from them is because it's more expensive.

You are mistaken about it being more expensive to purchase the phone through T-Mobile rather than Apple. Apple sets their prices and their sellers have to abide by that- that is why you rarely see Apple products on sale, iPhone or otherwise.

If you purchase a phone from Apple, though, you can use it on T-Mobile if you purchase the T-Mobile version or the unlocked version.