Update quantity with update (Shopping Cart)

Asked

Viewed 144 times

-3

I’m creating a shopping cart. This cart is without user and password, IE, it uses only the cart itself session that is created when the user chooses the product. After the customer chooses the product and clicks "GO TO CHECKOUT", the system makes an entry in the database of the products he chose (product name, description and value) and the order code becomes the customer’s session. So I can do a database search of the session created. The session code is also stored in the database, so I can search.

Entry code in the database:

                @$produto = $_POST['produto'];
                  if(isset($produto)) {
                      foreach ($produto as $reck) {
                        $consultaProduto = $conexao->query("SELECT * FROM produtos WHERE id = '$reck'");
                        while($exibeProdutos = $consultaProduto->fetch_assoc()){
                            $nome_produto = $exibeProdutos['nome_produto'];
                            $valor_produto = $exibeProdutos['valor'];
                            $descricao = $exibeProdutos['descricao_produto'];
                            $imagem = $exibeProdutos['imagem_produto'];
                            $pedidoReck = "200";
                            $horarioReck = date("h:i:s");
                            $pedidoLokos = "{$pedidoReck}{$horarioReck}";
                            $insereProduto = $conexao->query("INSERT INTO carrinho (numeroPedido, produto, descricao, valor) values ('$pedidoLokos','$nome_produto','$descricao','$valor_produto')");
                            $_SESSION['numero_pedido'] = $pedidoLokos;
                           /* if($insereProduto){
                              echo "Produto inserido";
                            }else{
                              echo "Produto não inserido". mysqli_error($conexao);
                            }*/

                          }
                        }

                        header("Location: carrinho.php");

                      } /*Fecha produto*/

After that, the customer/user is redirected to cart.php. In it, I make the query if the session is created and if it is the same as the one entered in the database, it will bring the products registered there.

Complete code of the trolley:

    <form action="" method="POST">
                    <div class="mad-products mad-product-small">

                      <?php
                         session_start();
                          header('Content-Type: text/html; charset=utf-8');
                          date_default_timezone_set('America/Sao_Paulo');
                          $conexao = new mysqli("xxxxxxxxxx","cardapio_cheirinbao","d#m14e4E","cardapio_cheirinbao");

                          if(!$conexao){

                            echo "Impossível se conectar ao banco de dados";
                            exit;
                          } 
                           $pedidoLokos = $_SESSION['numero_pedido'];
                            $consultaProduto = $conexao->query("SELECT * FROM carrinho WHERE numeroPedido = '$pedidoLokos'");
                            $valorTotal = 0; 
                            while($exibeProdutos = $consultaProduto->fetch_assoc()){
                                $nome_produto = $exibeProdutos['produto'];
                                $valor_produto = $exibeProdutos['valor'];
                                $valorVirgula = str_replace('.', ',', $valor_produto);
                                $valorTotal += $valor_produto;
                                $descricao = $exibeProdutos['descricao_produto'];
                                $imagem = $exibeProdutos['imagem_produto'];
                                $id = $exibeProdutos['id'];
                                $quan = $exibeProdutos['quantidade'];
?>
                      <div class="mad-col">
                        <!-- Product -->
                        <div class="mad-product">
                       <a href="excluirproduto.php?a=<?=$id?>" class="mad-close-item2"><i style="color:red;" class="fas fa-times"></i></a>
                          <a href="#" class="mad-product-image">

                            <?php

                            if($imagem){

                              echo "<img style='width:80px; height:80px;'' src='https://boahost.com.br/cheiro/adm/imagens/produtos/$imagem' alt=''>";

                            }else{

                            echo "";
                            }
                            ?>
                            <div class="quantity">
                          <input type="text" value="1" readonly="" name="quantidade_produto">
                          <button type="button" class="qty-plus"><i class="fas fa-plus fa-2x"></i></button>
                          <button type="button" class="qty-minus"><i class="fas fa-minus fa-2x"></i></button>
                        </div>
                            
                          </a>
                          <!-- product-info -->
                          <div class="mad-product-description">
                            

                            <a href="#" class="mad-product-title mad-link"><input type="hidden" value="<?=$id?>" name="id_produto"><?=$nome_produto;?> <sup style="color:#7a7879"> (<?=$quan;?>x)</a>
                           
                            <span class="mad-product-price">R$ <?=$valorVirgula;?></span>
                          </div>
                          <!--/ product-info -->
                        </div>
                        <!-- End of Product -->
                      </div>

<?php

                            }

                      ?>



                    </div>
                    <div class="sc-footer">
                        <div class="subtotal">Total do pedido: <span>R$  <?php echo number_format($valorTotal, 2, ',', ' '); ?></span> <span style="float:right;"><a href="excluir.php"> <i class="fas fa-sticky-note"></i> Limpar Carrinho </a> </span></div>
                        <button class="btn w-100"><span>Finalizar Pedido <i class="fa fa-shopping-bag fa-2x"></i> </span> <i><img src="https://velikorodnov.com/html/steakbreak_svg_icons/short_arrow_right.svg" alt="" class="svg"></i></button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

</form>

Note that in each product (in.php ), there is a quantity field so that the client/user can increase the amount:

 <div class="quantity">
                      <input type="text" value="1" readonly="" name="quantidade_produto">
                      <button type="button" class="qty-plus"><i class="fas fa-plus fa-2x"></i></button>
                      <button type="button" class="qty-minus"><i class="fas fa-minus fa-2x"></i></button>
                    </div>

A SCRIPT was created for when the client/user add increase the amount the system do an UPDATE there in the table of values and also of the quantity and present on the screen after doing this update. Behold:

<?php 



@$id_produto = $_POST['id_produto'];
@$quantidade = $_POST['quantidade_produto'];

if(isset($id_produto)):

$consultaProduto = $conexao->query("SELECT * FROM carrinho WHERE id = '$id_produto' AND numeroPedido = '$pedidoLokos'");
$atualizaValor = $consultaProduto->fetch_assoc();
$valorBanco = $atualizaValor['valor'];

$valorReal = $valorBanco * $quantidade;


$atualizaProduto = $conexao->query("UPDATE carrinho SET valor = '{$valorReal}', quantidade = '{$quantidade}' WHERE id = '{$id_produto}' AND numeroPedido = '{$pedidoLokos}'");

if($atualizaProduto){
  echo "Feito";
}else{
  echo "Desfeito";
}

endif;



?>

However, when the system is only updating the last product. For example: When I select 2 products, it brings correctly in cart.php. When I click on the quantity in the LAST product (increase the quantity) and click on "FINISH ORDER" it makes the change normally. However, when I try to make the change in other products apart from the last one it gives the message that it was successfully made but does not update. See the photo:

Aumento da quantidade somente no último produto

This way, I am not able to find a solution so that the program can make the update also in other products besides the last. How can I do it? Thank you.

1 answer

-1


You are not identifying the products that should have changed quantities when the button is pressed.

A suggested solution would be to change the components to the plus and Minus buttons using a link as did for the removal. For example, replace the two Buttons by the following lines

<a href="alterarquantidade.php?a=<?=$id?>&o=plus" class="qty-plus"><i class="fas fa-plus fa-2x"></i></a>

<a href="alterarquantidade.php?a=<?=$id?>&o=minus" class="qty-plus"><i class="fas fa-minus fa-2x"></i></a>

Note

  1. that in them I suppose the creation of the script alteraquantidade.php, specific to treat increasing or reducing the amount of products in the cart, same strategy you used to remove. And I also simulate the passage of the parameter o (thought in operation) passing whether the action is addition or subtraction (plu or Minus).
  2. that I am using the approach of every click the script to be called and in it you should redirect to the cart load again, as already happens with your current strategy, not to perform the page refresh would be necessary to use AJAX.
  • Just a question, how could I make the PLUS turn a number to multiply?

  • One idea would be to change the quantity field so that it allows the user to type in it (input text) and instead of Minus and plus, only put a change button Qtde

Browser other questions tagged

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