How to delete an item from the cart? - Session

Asked

Viewed 1,406 times

0

Hi, I’m making a shopping cart and I can’t seem to delete an item from Session. I’ve tried several ways, but I don’t understand why it doesn’t work. Could someone give me a light? (I’m new to php)

CODE:

<!DOCTYPE html>
<html lang="pt-br">

<head>
</head>
<?php
include("partials/conexao.php");
 session_start();
 if(!isset($_SESSION['carrinho']))
 {
    $_SESSION['carrinho'] = array();
   }

    //adiciona produto
    if(isset($_GET['add']))
    {
      //ADICIONAR CARRINHO

      if($_GET['add']) {
       $id = intval($_GET['add']);
      if(!isset($_SESSION['carrinho'][$id]))
      {
         $_SESSION['carrinho'][$id] = 1; }
      else{ $_SESSION['carrinho'][$id] += 1;
      }
    }


    //REMOVER CARRINHO
    if(isset($_GET['del'][$id]))
    {
      $id = intval($_GET['add']);
      if(isset($_SESSION['carrinho'][$id]))
      {
        unset($_SESSION['carrinho'][$id]);
      }
    }
    //ALTERAR QUANTIDADE
     if($_GET['add']) {
        if(is_array($_POST['prod'])){
          foreach($_POST['prod'] as $id => $qtd){
                     $id  = intval($id);
                     $qtd = intval($qtd);
                     if(!empty($qtd) || $qtd <> 0)
                     {
                        $_SESSION['carrinho'][$id] = $qtd;
                     }else{
                        unset($_SESSION['carrinho'][$id]);
                     }
                  }
               }
            }

      //ESVAZIAR carrinho
        if ($_GET['empty']){
          unset($_SESSION['carrinho']);

        }

         }


 <!-- carrinho menu-->
 <?php include("partials/header.php");?>

<div class="container">
  <div class="row">
    <section class="carrinhobg">
      <form action="carrinho.php" method="get" onsubmit="">
      <div class="txt-heading">Carrinho
        <a id="btnEmpty"
        href="carrinho.php?empty"/>Esvaziar carrinho</a>
      </form>
      <form action="carrinho.php" method="post">
      </div>

        <table id="cart" class="table table-hover table-condensed">
          <?php
          if(count($_SESSION['carrinho']) == 0){ ?>
            <?php echo '<h4 class="nomargin"> Não há produto no carrinho </h4>'; ?>
            <?php }
            else {
              $total = 0;
              foreach($_SESSION['carrinho'] as $id => $qtd){
                $sql   = "SELECT *  FROM vw_produtos WHERE cd_produto= '$id'";
                $qr    = mysql_query($sql) or die(mysql_error());
                $ln    = mysql_fetch_assoc($qr);

                $nome  = $ln['nm_produto'];
                $preco = number_format($ln['vl_produto'], 2, ',', '.');
                $sub   = number_format($ln['vl_produto'] * $qtd, 2, ',', '.');

                $total += $ln['vl_produto'] * $qtd;
                ?>
                        <thead>
                  <tbody>
                            <tr>
                                <th style="width:50%">Produto</th>
                                <th style="width:10%">Preço</th>
                                <th style="width:8%">Quantidade</th>
                                <th style="width:22%" class="text-center">Subtotal</th>
                                <th style="width:10%">Retirar da cesta</th>
                            </tr>

                        </thead>

                            <tr>
                                <td data-th="Produto">
                                    <div class="row">

                                        <div class="col-sm-2 hidden-xs">
                      <img src="img/produtos/<?php echo $ln['imagem']?>" alt="..." class="img-responsive"/></div>

                      <div class="col-sm-10">
                                            <h4 class="nomargin"><?php echo $ln['nm_produto']?></h4>
                           <p class=""> <?php echo $ln['ds_produto']?>
                             </p>
                                        </div>

                                </td>
                                <td data-th="Preço"> <?php echo $ln['vl_produto']?>  </td>
                                <td data-th="Quantidade">
                    <input type="number" class="form-control text-center" name="prod"<?php echo '['.$id.']" value="'.$qtd.'"'?>""/>

                                </td>
                                <td data-th="Subtotal" class="text-center"> <?php echo 'R$' .$sub; ?> </td>
                                </td>
                </form>
                <?php //$id = $_GET['add']; ?>
                <form class="carrinho.php" method="get">
                  <td data-th="excluir" class="text-center">
                    <a href="carrinho.php?del=<?php echo $id; ?>"/> Excluir </td>
                    </tr>
                </form>
            </div>
                        </tbody>
                        <tfoot>
                <?php } ?>
                            <tr>
                                <td><a href="produtos.php" class="btn btn-warning">
                    <i class="fa fa-angle-left"></i> Continue comprando</a></td>
                                <td colspan="3" class="hidden-xs"></td>
                                <td class="hidden-xs text-center" ><strong>
                      <?php echo 'Total: '.'R$' .$total; ?>
                      </strong>
                    </td>
                    <?php  } ?>
                  </tr>
                </tbody>
                  </tfoot>
                </table>
                  <div class="comprar">
                    <a href="#" class="btn btn-default btn-lg" onclick="javascript: location.href='pedido-final.php'">Comprar</a>
                  </div>
                  <div class="att">
                    <a href="carrinho.php" class="btn btn-default btn-lg" onclick="<?php
                     echo "<meta HTTP-EQUIV='refresh' CONTENT='3;URL=carrinho.php'>";
                    ?>">Atualizar carrinho</a>
                  </div>
            <hr />
            <div class="table">
                            <thead>
                            <tr>
                            <th style="width:50%"><b>CALCULAR FRETE</b></th>
                            </tr>
                            </thead>
                                 <div id="custom-search-inputii">
                                                  <div class="input-group col-md-12">
                                                      <input type="text" class="search-query form-control" placeholder="Digite um cep válido" />
                                                      <span class="input-group-btn">
                                                          <button class="btn btn-default btn-md" type="button">
                                                              Calcular
                                                          </button>
                                                      </span>
                                                  </div>
                                              </div>
                                            </div>
                                        </section>
 <!--/.CONTAINER .ROW -->
                 </div>
                 </div>
         <!-- Footer -->

     <!-- /.container -->
</body>
</html>

1 answer

2


You who are starting out, it is VERY important to maintain a standard of indentation of the code -- are those spaces that we put, when opening a {} for example. This will help you to locate simple errors as one that is in this code.

//adiciona produto
if(isset($_GET['add']))
{
    //ADICIONAR CARRINHO

    if($_GET['add']) {
        $id = intval($_GET['add']);
        if(!isset($_SESSION['carrinho'][$id]))
        {
            $_SESSION['carrinho'][$id] = 1;
        } else {
            $_SESSION['carrinho'][$id] += 1;
        }
    }


    //REMOVER CARRINHO
    if(isset($_GET['del'][$id]))
    {
        $id = intval($_GET['add']);
        if(isset($_SESSION['carrinho'][$id]))
        {
            unset($_SESSION['carrinho'][$id]);
        }
    }

Note that the code that includes and excludes are inside the block of the same if , what tests whether an addition command has been sent if (isset($_GET['add']))

It is also important to review the logic.

You get the "id" you want to delete in this snippet $id = intval($_GET['add']);

and to exclude:

if(isset($_GET['del'][$id]))
{
    $id = intval($_GET['add']);

Noticed? You are trying to get the ID in the variable that should "add".

Review your code, and gradually test. If you need to, start from scratch with each function: add, Edit, del, clean.

Good studies!

  • 1

    Thank you so much! I changed it and it worked. I’ll take your advice not to happen again. Thanks! ;)

  • 1

    It is worth noting that mysql_query is deprecated and is only included until PHP 5. Other alternatives are mysqli and Pdo_mysql. (http://php.net/manual/en/mysql.php)

  • 1

    @Júliacristina good tip from @Lipespry ! Learn how to use the PDO which is a more modern library. This site PHP The Right Way has several important tips on modern PHP!

  • Thanks for the tip! I started studying PDO a few days ago. I will go to the site p/ learn more. @Lipespry

  • 1

    @Júliacristina The idea of lucasvscn is good! O PDO loses in performance, compared to mysqli. But it’s so little PDO functionality and compatibility with others Databases. My recommendation is to invest in POO. A EXCELLENT course FREE is from Video Course: (https://www.youtube.com/playlist?list=PLHz_AreHm4dmGuLII3tsvryMMD7VgcT7x).

Browser other questions tagged

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