I know this may be a stupid question but I am not very experienced with SQL Joins and I don't want to do it without fully knowing that it is the right thing to do.
I have created a recipe site which have different categories like bread, biscuits, cake etc. these are all in the category table of the database. I have recipes in the recipe table.
The problem I am facing is, on the category page, since each category has its own ID I created one page where each categories redirect to and used this code
<a href="index.php?p=selected&id=<?php echo $recipe['cat_id']; ?>">
This one page features different categories based on the ID, the id is changed in the url so for the bread category it would look like this:
index.php?p=selected&id=1
So, since there is one page for each category I want it to display the recipes, I used this code:
$query = "SELECT * FROM recipes ORDER BY recipe_id ASC";
but this displays every recipe in the database, what I want is for it to display the recipe based on the category it is in like below:
$query = "SELECT * FROM recipes WHERE cat_id = :id ORDER BY recipe_id ASC";
The cat_id is part of the category table, so do I need to join this table to the recipe table to make it work?
Be sure to tell me if I have missed something,
Thank you for your time.
yes you have missed something must add column cat_id in recipes table which equal cat_id in category table when you add item in recipes table and then it simple
$query = "SELECT * FROM recipes
WHERE recipes.cat_id = :id";
or
$id = intval($_GET['id']);
$query = "SELECT * FROM recipes
WHERE recipes.cat_id = $id";
If one recipe one category then,
SELECT * FROM recipes inner join category
on category.id=recipe.cat_id
where cat_id = :id ORDER BY recipe_id ASC";
If one cateory many recipes then
SELECT * FROM recipes leftjoin category
on category.id=recipe.cat_id
where cat_id = :id ORDER BY recipe_id ASC";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.