Buying stock is a little like asking a neighbor to buy something for you at a store. With stocks, you give the neighbor, called a broker, an order saying what you want to buy and perhaps how much you're willing to pay. The broker puts that order through some trading system and buys the stock for you. Different trading systems basically match stock buyers with sellers.
Find the Market
Almost all stocks are bought through brokers, who are representatives licensed to do business with the various markets where stocks are listed and traded. When you place an order with a broker, the representative first determines where the stock is listed, such as the New York Stock Exchange or the NASDAQ electronic trading system.
The local representative you deal with passes the order along through brokerage channels to the appropriate market. On the NYSE, for instance, that goes to a brokerage representative called a floor broker, who takes it to the place on the trading floor where that stock is bought and sold. Your "buy" order is matched with a "sell" order from a stockholder who wants to sell that stock.
Matching Buy, Sell
If yours is a "market" order, an exchange representative called a specialist matches it with a sell order at what is essentially an agreed-on price. It's the specialist's job to match orders at appropriate prices. If there are too few "sell" orders to match, he is obligated to sell you shares from his personal inventory. If you entered a "limit" order that specified a price to pay, the order is held until a sell order matches that price.
NASDAQ works a bit differently. Instead of seeking a matching sell order on a trading floor, your broker will send the order to a "market maker," a broker who warehouses that specific stock. The market maker fills the order by selling stock from her inventory, at whatever price she is charging at that time. If it is a "limit" order with a specified price, the market maker either matches that price or holds it until she is willing to meet that price.
Supply and Demand
Stock trades are classic examples of supply and demand. If a lot of people want a stock, the price they are willing to pay will increase. If more people want to sell a stock than there are buyers, the price will drop. Stocks start with an initial price, set when the company first makes shares available publicly, but once trading begins, supply and demand set the price.
A few stocks are sold directly by companies just starting in business and seeking to sell shares in the company to raise initial capital. Another class of stock is "over the counter," usually low-priced shares in small companies that are sold directly by various individuals or brokers. These "penny stock" deals are not publicly reported or regulated like formal trading systems are.