When you buy a stock you're buying a piece of the company. When a company needs to raise money, it issues shares. This is done through an initial public offering (IPO), in which the price of shares is set based how much the company is estimated to be worth, and how many shares are being issued. The company gets to keep the money raised to grow its business, while the shares (also called stocks) continue to trade on an exchange, such as the New York Stock Exchange (NYSE).
Traders and investors continue to buy and sell the stock of the company on the exchange, although the company itself no longer receives any money from this type of trading. The company only receives money from the IPO.