How to create a real-time list with PHP and Ajax

Asked

Viewed 89 times

0

I’m creating a recipe site, where the ingredients will be registered individually in a table, referencing the recipe id, example of how the tables are:

ptp_receitas
id|nome
1 |receita de feijão

ptp_receitas_ingredientes
id|id_receita|ingrediente
1 |    1     | feijão
2 |    1     | bacon
3 |    1     | cebola

I created a form that inserts the values in the database, but I don’t know how to insert each ingredient in a new line.

I thought of something with ajax, putting an input "ingredient" that adds the values in a multiple select, and after registering the recipe, it takes each value from that list and inserts a line into the ingredients ptp_receitas_ingredients, something like that:

<input id="ingrediente">
<button id="add_ingrediente" type="button">Adicionar Ingrediente</button>
<select id="ingredientes" multiple>
</select>
<input id="nome_receita">
<button id="cadastrar_receita" type="submit">Cadastrar Receita</button>

Is that the line of reasoning for my need? Or is there another way to do it?

Thank you!

  • Post the php you use to insert into the bank, it is necessary to formulate a proper response

1 answer

0

The line of reasoning is simple. Its bank structure has two tables, one of which has a foreign key (FK) referencing the other in a 1->n relationship.

To enter these records, you must follow the following INSERT order

  1. INSERT in table "ptp_recipes"
  2. Recovers the ID that has just been inserted (there are several ways to do this, it depends on what technologies you are using)
  3. Do the INSERT’s in table "ptp_receitas_ingredients" using the received form data and the previously recovered ID.

In these steps, each INSERT will actually have to be run individually.

You can send all data to the back-end and there organize the INSERT instructions that will be executed or you can make an AJAX request for each instruction in serial mode, as long as it respects the order above.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.