ultigma Posted August 1, 2013 Share Posted August 1, 2013 (edited) Hello, I'm new to php and i'm trying to figure out the best way to structure a database about animals. Basically i have a blog database called 'posts' with int | text | text | int ------------------------------------------------- ' id ' | ' title ' | ' content ' | ' category ' and what I want to happen is that depending on the category show only them posts. For example would this be the right way to do it; 1 - Dogs 2 - Cats 3 - Birds 4 - Fish "SELECT * FROM posts WHERE category = 1" to display everything for dogs OR Should I change category to varchar and explicitly call them ' Dog ' - ' Cat ' - ' Bird ' I would prefer the latter as having it explicitly called makes more sense to me. Thanks for anyone that can help =) Edited August 1, 2013 by ultigma Quote Link to comment https://forums.phpfreaks.com/topic/280719-database-design-help-creating-subject-categories/ Share on other sites More sharing options...
requinix Posted August 1, 2013 Share Posted August 1, 2013 (edited) The first one with numbers is correct. You should actually have another table for the categories too id | category ---+--------- 1 | Dogs 2 | Cats 3 | Birds 4 | Fishso if you really wanted to search by name it would be SELECT p.* FROM posts p JOIN categories c ON p.category = c.id WHERE c.category = "Dogs"But most of this should be happening automatically: you show all the categories in a list, their links go to some page using the category ID, and that page shows whatever posts are in that category. You don't specify "Dogs" or "Birds" anywhere but have the code output it. Example: echo "<ul>"; foreach (/* SELECT id, category FROM categories ORDER BY category */ as $row) { echo "<li><a href='/posts.php?category=", $row["id"], "'>", $row["category"], "</a></li>\n"; } echo "</ul>"; // links to the posts under the category $category = (int)$_GET["category"]; echo "<ul>"; foreach (/* SELECT id, title FROM posts WHERE category = $category */ as $row) { echo "<li><a href='/post.php?id=", $row["id"], "'>", $row["title"], "</a></li>\n"; } echo "</ul>"; Edited August 1, 2013 by requinix Quote Link to comment https://forums.phpfreaks.com/topic/280719-database-design-help-creating-subject-categories/#findComment-1443014 Share on other sites More sharing options...
ultigma Posted August 1, 2013 Author Share Posted August 1, 2013 Ah ok, in that case i'll create a category table and reference that in the 'posts' > 'category' table. I think I need a bit of training on relational databases and get my head round how they are best used Thanks again =) Quote Link to comment https://forums.phpfreaks.com/topic/280719-database-design-help-creating-subject-categories/#findComment-1443062 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.