TIP: The var_dump() function is your friend here. Add something like the following in your source code to see how the data is structured.
echo "\n</pre>"; die;
This also show you whether you are actually doing your SQL query correctly. It has happened to me more than once where I am trying to format the output of an SQL query just to discover that it didn't contain the information I expected.
Once you understand what is being returned, it will become a lot easier for you to write a loop to extract and format the information you need.
You can actually do this with just about any variable containing almost any simple or complex structured information in PHP.
Hope this useful.