Add multiple products to a single mysql order

Asked

Viewed 565 times

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 the mysqli_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 :)

  • Yes I have @Milk , is within a foreach this is the following code foreach($_SESSION['carrinho'] as $cada_item) { .... if(isset($_POST['pagamento'])) { ... } } in my case the products are in a session!

  • So this is it :) This foreach can move to contain only the line $sql3=mysqli_query(..etc

  • So you’re saying I should eliminate the previous foreach, and put another one just to contain that line?

  • Yeah, I’m just putting it as a comment to make it easier to read.

  • 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 :(

  • If you like, and if you don’t mind, of course, we can continue this discussion in chat.

Show 2 more comments

2 answers

2


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. Place an order;
  2. Fetch the id the package was stored with (you already do, but you can use the mysqli_insert_id instead of running a new query
  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 may be on $_SESSION, in the $_POST, in $_COOKIES or even in a temporary table of the database, as you have developed.

Considering the comment you left behind, what you need to do is (remove the cycle you have before the if and moves it to include only the execution of $sql3

$erros = [];
foreach($_SESSION['carrinho'] as $cada_item) {
    //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) {
        // como nao é ideal fazer echo aqui
        // podes sempre guardar num array e mais tarde mostrar
        //echo "Erro ao inserir na tabela";
        $erros[] = "Erro ao inserir produto: {$item_id}";
    }
}
  • As I mentioned, I can not remove the cycle before the if, as it will not show me more products, would have to change the whole code...

  • I left a message in the chat. But you can repeat the cycle more than once. 1 to list, the other to enter in the database. Actually, the if (isset($_POST['pagamento'])) you can put it at the top of your file because it will only be executed when the form is submitted.

2

Basically you have to return the generated key to the submitted order and then make a loop by products assigning the same key. Example:

// inserir a encomenda
$sql = "INSERT INTO encomenda (...) VALUES (...)";
mysql_query($sql,$conn );
// retornar o último id
$id_encomenda = mysql_insert_id( $conn );

//percorrer as linhas através do $_POST recebido
foreach ($_POST as $k=>$v) {
    // inserir linhas da encomenda
    $sql = "INSERT INTO prod_encomenda (...) VALUES ($id_encomenda,...))";
    mysql_query($sql,$conn );
}
  • Through the $_POST? In my case I am using a session, also serves?

  • Sure, @Ana. Enough foreach($_SESSION AS $key => $value) { ... }

  • Without success... He continues to do the same, inserts an order for each product...

Browser other questions tagged

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