Could you please just explain what you are trying to do instead of showing code that probably isn't correct? Maybe show a screenshot of the page? Or give us the URL of a live page to look at?
And you have no code in there at all to account for null values.
And you don't say what database you are using. Yes, it can make a BIG difference.
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.