Search code examples
phpmysqlsqlrelational-databasedatabase-normalization

Need help adding rows to cross-reference table


I'm writing a recipe script (php/mysql) for my kitchen app, using these tables:

ingredients
-----------
ingredient_id (PK)
ingredient_name

(An ingredient can be part of many recipes)

recipes
-------
recipe_id (PK)
recipe_name

(A recipe can have many ingredients)

recipe_ingredients_map
---------------------
recipe_id_map (FK)
ingredient_id_map (FK)

When adding a new recipe, I'll need to insert a row into the recipe_ingredients_map table for each ingredient in the recipe. I'm having trouble figuring out how to write the query for all of this. Save me, please? =P


Solution

  • Do not try to write a insert query for all 3 tables.

    • First insert a recipe.
    • Next insert some ingredients.
    • Finally link then together in in the recipe_ingredients_map.

    Your recipe_ingredients_map is missing a primary key.

    If it is desired you can wrap it all up in a transaction.