After you run your query, look at the record count. Run all
the if/else logic you have to to determine the number of columns
you want. Don't worry about the number of rows, that will take care
of itself.
Once you have the number of columns figured out, output your
data as simply as possible, no style tags, no links, just data. Use
the modulus operator to decide when to start a new row.
Once you've accomplished that, start adding the rest of your
stuff.