1
Good afternoon
I have two tables encomenda
and prod_encomenda
. My goal is to assign to one order several products. Both contain the id_encomenda
, so I guess the structure of the tables is well done!
What I want exactly is for example:
Order
id_order = 1
Prod_encomenda
id_product = 20; id_order=1;
id_product = 42; id_order=1;
For that I did something like this:
if (isset($_POST['pagamento'])) //ao carregar no botão efetuar pagamento os dados serão inseridos na tabela encomenda e prod_encomenda
{
//INSERIR NA TABELA ENCOMENDA
$inserir=mysqli_query($link,"INSERT INTO encomenda (id_encomenda,email, data_encomenda) VALUES ('','".$_SESSION['user']."','$data')");
if (!$inserir)
{
echo "Erro ao inserir na tabela";
}
$sql2=mysqli_query($link,"SELECT id_encomenda from encomenda where email='".$_SESSION['user']."'");
$registos_id_encomenda=mysqli_num_rows($sql2);
while ($registos_id_encomenda!=0) {
$get_id_encomenda=mysqli_fetch_array($sql2);
$registos_id_encomenda--;
}
//INSERIR NA TABELA PROD_ENCOMENDA
$sql3=mysqli_query($link,"INSERT INTO prod_encomenda (id_encomenda, id_produto, quantidade, preco_total) VALUES ('".$get_id_encomenda[0]."', '$item_id','".$each_item['quantidade']."','$producttotalpricetotal')");
if (!$sql3) {
echo "Erro ao inserir na tabela";
}
But clearly when entering for example 3 products, it generates 3 orders in the database, instead of just one order for the 3 products.. Thanks in advance!
Do you have a loop that encompasses the code that’s inside the
if (isset($_POST['pagamento']))
? The code of @Nuno Gonçalves is 'more or less' what you have to do. 1. Insert Order; 2. Fetch the generated id using themysqli_insert_id
for this; 3. A loop to insert each product that was in the shopping basket using as a foreign key the id of step 2. The products can be in $_SESSION, $_POST, $_COOKIES or even a temporary table of the database, as you have developed :)– Leite
Yes I have @Milk , is within a
foreach
this is the following codeforeach($_SESSION['carrinho'] as $cada_item) { .... if(isset($_POST['pagamento'])) { ... } }
in my case the products are in a session!– Ana
So this is it :) This foreach can move to contain only the line
$sql3=mysqli_query(..etc
– Leite
So you’re saying I should eliminate the previous foreach, and put another one just to contain that line?
– Ana
Yeah, I’m just putting it as a comment to make it easier to read.
– Leite
The problem is that if I eliminate this foreach that is before the
if(isset)
will no longer generate the products, so I can view them :(– Ana
If you like, and if you don’t mind, of course, we can continue this discussion in chat.
– Ana