The problem really is in query:
SELECT * FROM category, product WHERE category.category_id = product.category_id AND product.product_id IN (pid) ORDER BY category.last_category ASC
pid means nothing to MySQL. If you wanted it to be a value as a string it has to be quoted with single quotes (')...
If you need it to be a number then something went wrong because clearly you don't have a number there...
Forgive Roger on his harsh words, but he has the point: the code is just too hard to analyze when it is not printed with PHP highlighting...
Again, to learn how to use VB code that allows you to do it go here...
Even if it is a small part of code, but to have this large part of code just printed out, it's impossible to see everything...
It may be O.K. for you to look at it, because you wrote it, but for us - it is hard and many won't even bother...