I am producing a site for a book seller, and have now been supplied with a list of subcategories to complement the categories that I was already using.
My categories and subcategories are all stored in one table (categories) with the columns - id(INT), cat_type(INT) and category(TEXT). The cat_type column connects subcategories to their categories, ie a row with cat_type 0 is a category and a row with any other cat_type is a subcategory of the category whose id matches the cat_type. This is all fine and I can extract a list of subcategories that belong to a particular category to populate a selection menu once the user has chosen a category.
However, if the user doesn't then select a subcategory I would like to display all the books within that category and it's relevant subcategories. This is what I have for the query:
$query_category = sprintf("SELECT DISTINCT category.category, category.cat_type, book_type.type, books.id, books.type_id, books.category_id,
books.title, books.author, books.author2, books.author3, books.`year`, books.pages, books.price, books.oldprice,
books.pic
FROM category, books, book_type
WHERE (books.category_id = category.id OR books.category_id = category.cat_type)
AND (category.id = %s OR category.cat_type = %s)
AND books.type_id = book_type.id ORDER BY books.title ASC", $catid_category, $catid_category);
This works fine unless there are books that only belong to the category and not a specific subcategory, when each book is listed four times. Ideally, all books will be assigned to a subcategory, but it is possible that they won't so I need this to work.
Apologies for the ridiculously long post, but any help would be greatly appreciated. 🙂