How to have a grid layout when extracting data from MYSQL instead of linear layout?

I really want to have this functionality in my upcoming site but as you know i had just learnt PHP and MYSQL, so that’s why i am not a perfect at handling problems related to PHP. As per the regular tutorial available on the internet one can extract data from MYSQL in a linear way but i want to extract in a grid fashion. For this i googled it but haven’t got any meaningful result.

For this use the following code for extraction:

code

There is only one flaw in the above program that it violates the conditions of the HTML 5 standard which requires all the html tags to be closed with proper closing tags but it cannot be done here. If you have any better solution than please share with us in the comments below.