How to clear shopping cart after checkout

Asked

Viewed 398 times

1

I created a shopping cart, where in a table it lists all products in the database and as the user clicks to add it includes in the cart (which is another table below the list of products, on the same page).

Everything is working, however when he finalizes the purchase and recharges the page he more products that were added in the cart. I’d like you to clean the cart.

NOTE: I’m doing everything on the same page in PHP + Html

Code:

<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
include_once("conexao.php");

if (!isset($_SESSION['listaproduto'])) {
    $_SESSION['listaproduto'] = array();
}
if (isset($_GET['acao'])) {
    if ($_GET['acao'] == 'add') {
        $id = intval($_GET['id']);
        if (!isset($_SESSION['listaproduto'][$id])) {
            $_SESSION['listaproduto'][$id] = 1;
            header("Location: http://localhost:8081/oneschool-master/carrinho.php");
        } else {
            $_SESSION['listaproduto'][$id] += 1;
            header("Location: http://localhost:8081/oneschool-master/carrinho.php");
        }
    }
}
if ($_GET['acao'] == 'del') {
    $id = intval($_GET['id']);
    if (isset($_SESSION['listaproduto'][$id])) {
        unset($_SESSION['listaproduto'][$id]);
        header("Location: http://localhost:8081/oneschool-master/carrinho.php");
    }
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <div class="site-logo mr-auto w-25"><title>ImperialCalçados</title></div>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="https://fonts.googleapis.com/css?family=Muli:300,400,700,900" rel="stylesheet">
    <link rel="stylesheet" href="fonts/icomoon/style.css">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/jquery-ui.css">
    <link rel="stylesheet" href="css/owl.carousel.min.css">
    <link rel="stylesheet" href="css/owl.theme.default.min.css">
    <link rel="stylesheet" href="css/owl.theme.default.min.css">
    <link rel="stylesheet" href="css/jquery.fancybox.min.css">
    <link rel="stylesheet" href="css/bootstrap-datepicker.css">
    <link rel="stylesheet" href="fonts/flaticon/font/flaticon.css">
    <link rel="stylesheet" href="css/aos.css">
    <link rel="stylesheet" href="css/style.css">
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
    <script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
  </head>
<body>
  <div class="site-section bg-image overlay" style="background-image: url('images/vitrini.jpg');">
      <div class="container">
        <div class="row justify-content-center align-items-center">
          <div class="col-md-8 text-center testimony">
          </div>
        </div>
      </div>
    </div>
  <div class="site-section" id="teachers-section">
      <div class="container">
        <div class="row mb-5 justify-content-center">
          <div class="col-lg-7 mb-5 text-center"  data-aos="fade-up" data-aos-delay="">
            <h2 class="section-title">Lista de Produtos</h2>
          </div>
        </div>
        <?php
$sql                = "select codigo,descricao,valor from loja.produto order by codigo"; # LIMIT $inicio, $qnt_result_pg";
$resultado_produtos = mysqli_query($conn, $sql);
?>
 <table class="table table-hover" id="tabres">
    <thead>
      <tr bgcolor="#AAAAAA">
        <td>Código</td>
        <td>Descrição</td>
        <td>Valor</td>
        <td>Adicionar</td>
      </tr>
    </thead>
    <tbody id="lsprodutos">
    <?php
while ($row_produto = mysqli_fetch_assoc($resultado_produtos)) {
    echo '<tr>
                          <td>' . $row_produto['codigo'] . '</td>
                          <td>' . $row_produto['descricao'] . '</td>
                          <td>' . $row_produto['valor'] . '</td>
                          <td><a href = "carrinhocompras.php?acao=add&id=' . $row_produto['codigo'] . '"><i class="icon-plus"> </i></a></td>
                          
           </tr>';
}
?>
   </tbody>
  </table>
  <hr>
<table class="table table-hover" id="tabcar">
<div class="row mb-5 justify-content-center">
          <div class="col-lg-7 mb-5 text-center"  data-aos="fade-up" data-aos-delay="">
            <h2 class="section-title">Carrinho de Compras</h2>
          </div>
        </div>
      <thead>
        <tr  bgcolor="#AAAAAA">
          <td>Codigo</td> 
          <td>Descriçao</td>
          <td>Valor</td>
          <td>Qntd</td>
          <td >Total R$</td> 
          <td>Remover</td>
        </tr>
      </thead>
          <form action="?acao=up" method="post">
      <tbody>
          <?php
if (count($_SESSION['listaproduto']) == 0) {
?>
               <div align="center">
                <?php
    echo "<h3><b>Não ha produtos no carrinho</b></h3>";
?>
               </div>
                <?php
} else {
    require("conexao.php");
    foreach ($_SESSION['listaproduto'] as $id => $qtd) {
        $sql = "SELECT * FROM produto WHERE codigo= '$id'";
        $qr = mysqli_query($conn, $sql) or die(mysqli_error());
        $ln = mysqli_fetch_assoc($qr);
        
        $codigo    = $ln['codigo'];
        $descricao = $ln['descricao'];
        $valor     = $ln['valor'];
        $total     = $ln['valor'] * $qtd;
        $subTotal += $total;
        echo '<tr>
                          <td>' . $codigo . '</td>
                          <td>' . $descricao . '</td>
                          <td>' . $valor . '</td>
                          <td><input type="text" size="2" name="prod[' . $id . ']" value="' . $qtd . '" /></td>
                          <td>' . $total . '</td>
                          <td><a href="?acao=del&id=' . $id . '"><i class="icon-minus"> </i></a></td>
                        </tr>';
    }
}
?>
     </tbody>
<?php
require("conexao.php");
if (isset($_POST['enviar'])) {
    $SqlInserirVenda = mysqli_query($conn, "insert into venda(valorTotal) Values('$subTotal')");
    $IdVenda         = mysqli_insert_id($conn);
    
    foreach ($_SESSION['listaproduto'] as $ProdInsert => $Qtd):
        $SqlInserirItens = mysqli_query($conn, "Insert into itensvenda(IdVenda,IdProduto,Qtde) Values('$IdVenda','$ProdInsert','$Qtd')");
    endforeach;
    echo "<script>alert('Venda Concluída')</script>";
}
?>
</table>
<div align = "right">
<form action="" enctype ="multipart/form-data" method="post">
      <?php
echo '<h3> Total: R$' . number_format($subTotal, 2, ",", ".") . ' </h3>';
?>
     <input type="submit" name="enviar" value="Finalizar Pedido" />
</form>  
</div>
<br>
</div>
<div class="form-group">
    <div class="site-section bg-image overlay" style="background-image: url('images/vitrini.jpg');">
      <div class="container">
        <div class="row justify-content-center align-items-center">
          <div class="col-md-8 text-center testimony">
          </div>
        </div>
      </div>
    </div>
    <div class="site-section pb-0">
      <div class="future-blobs">
        <div class="blob_2">
          <img src="images/blob_2.svg" alt="Image">
        </div>
        <div class="blob_1">
          <img src="images/blob_1.svg" alt="Image">
        </div>
      </div>
        <div class="row pt-5 mt-5 text-center">
          <div class="col-md-12">
            <div class="border-top pt-5">
            <p>
        <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. -->
        Copyright &copy;<script>document.write(new Date().getFullYear());</script> Imperial Calçados <i class="icon-heart" aria-hidden="true"></i>
        <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. -->
      </p>
      <input type="button" value="Inicio" onClick="window.location.href = 'index.php'"style="color: #FFFFFF; background-color: #CC0000"> 
                <input type="button" value=" Sair  " onCLick="window.location.href = 'sair.php'" style="color: #FFFFFF; background-color: #CC0000"> 
            </div>
          </div>      
        </div>
      </div>
  </div> <!-- .site-wrap -->
  <script src="js/jquery-3.3.1.min.js"></script>
  <script src="js/jquery-migrate-3.0.1.min.js"></script>
  <script src="js/jquery-ui.js"></script>
  <script src="js/popper.min.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script src="js/owl.carousel.min.js"></script>
  <script src="js/jquery.stellar.min.js"></script>
  <script src="js/jquery.countdown.min.js"></script>
  <script src="js/bootstrap-datepicker.min.js"></script>
  <script src="js/jquery.easing.1.3.js"></script>
  <script src="js/aos.js"></script>
  <script src="js/jquery.fancybox.min.js"></script>
  <script src="js/jquery.sticky.js"></script>
  <script src="js/main.js"></script>
</html>

Thanks in advance!

2 answers

-1

From what I understand, you use the session to save the items in the shopping cart. So what you have to do is clear the session after inserting the sale:

I believe that this is where the sale is included in the database:

if (isset($_POST['enviar'])) {
    $SqlInserirVenda = mysqli_query($conn, "insert into venda(valorTotal) Values('$subTotal')");
    $IdVenda         = mysqli_insert_id($conn);

    foreach ($_SESSION['listaproduto'] as $ProdInsert => $Qtd):
        $SqlInserirItens = mysqli_query($conn, "Insert into itensvenda(IdVenda,IdProduto,Qtde) Values('$IdVenda','$ProdInsert','$Qtd')");
    endforeach;
    unset($_SESSION['listaproduto']); // Aqui a sessão de lista de produtos é limpa
    echo "<script>alert('Venda Concluída')</script>";
}
  • Thanks for the help, it continues inserting but do not destroy the session at all

-1

Carlos,

Do the following, after inserting it into your bank, check if it was done through if and clear the session:

//$insere será a variável com o true ou false da inserção
if($insere) {
    //Se os dados foram gravados, destroi a sessão e envia para uma página que tu queira
    session_destroy($_SESSION['NomeDaSessao'];
    header('Location: paginadesejada.html');
} else {
    //Caso tenha dado erro na hora da inserção, apresente uma mensagem ou envie para uma página de erro que tu queira.
    echo("Erro");
}
  • now besides not cleaning does not enter the sale

  • I’ll change it to make it simpler

Browser other questions tagged

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