Problem -> Shopping Cart increases products by refreshing the page - PHP

Asked

Viewed 206 times

0

From the series "I’m trying to make a complete shopping cart system" kk, I have one more problem. Just to emphasize that I’m a beginner in programming and I’m studying the maximum functionality and one of them is related to shopping cart so I usually ask a lot of questions about the same.

I’ll explain my problem but first I’ll tell you how the system is:

BRIEF EXPLANATION:

I have the shopping cart taking the products from the database and entering on the application front. So there is also the functionality add amount of a same product, this is ok. It’s that basic thing, if there is already an array with an item, it increases 1 more and so on. To remove it is all right. Now comes the pump ^^

PROBLEM:

My problem is two things: 1º When I add a product or remove, it refreshes the page and my idea is that it does not do this refresh but do in Run Time;

2nd Consider the example: Microphone Price: 30,00 Qtof: 1;

Webcam Price: 22,00 Qty: 3; { <===== This was the last product added, 3 quantity of the second product.}

The problem is that if I give an Update, it sends again the request to add item and increments +1 in the last product added.

Am I clear? I always think I explain in my own way and it’s all fucked up but just say there that I "translate" kkkk

Well, those are my problems, and not to get into my words haha, I’ll add the code to my cart, blz? Remembering that I know that possibly the error is in relation to SESSION’s but I still do not understand all the application and way to apply that it has so I count on a lot of help from you. Follows code:

<?php
/* Inicializa uma sessão */
//session_start();

/* Verifica se já existe uma sessão ativa */
if(!isset($_SESSION['itens'])){
    $_SESSION['itens'] = array();
}

/* Inicializa uma sessão */
if(isset($_GET['add']) && $_GET['add'] == 'carrinho'){
    $idProduto = $_GET['id'];
    if(!isset($_SESSION['itens'][$idProduto])){
        $_SESSION['itens'][$idProduto] = 1;
    }else{
        $_SESSION['itens'][$idProduto] += 1;
    }
}

/* Mostrar carrinho de compras */
echo "<div>";
if(count($_SESSION['itens']) == 0){ /* Se a sessão itens estiver vazia, retorna uma mensagem */
    echo "<div style='display : relative; float : right;'>Carrinho Vazio<br/><a href='index.php'>Adicionar Itens</a>";
}else{
    /* Cria conexão e retorna os na session itens os produtos e suas info como um array. */
    $conection = new PDO('mysql:host=localhost;dbname=lanchenet', 'admin', 'nuttertools'); 
    foreach($_SESSION['itens'] as $idProduto => $qtde){
        $query = $conection->prepare("SELECT * FROM produto WHERE id=?");
        $query->bindParam(1, $idProduto);
        $query->execute();
        $produtos = $query->fetchAll();
        $total = $qtde * $produtos[0]["valor"];
        echo
            $produtos[0]["nome"].'<br/>
            Preço: '.number_format($produtos[0]["valor"], 2, ",", ".").'<br/>
            Quantidade: '.$qtde.'<br/>
            Total: '.number_format($total, 2, ",", ".").'
            <a href="sistema.php?p=cardapio&remover=carrinho&id='.$idProduto.'">Remover</a>
            ';
        ;
    }
 echo "</div>";
 echo "</div>";
}

if(isset($_GET['remover']) && $_GET['remover'] == 'carrinho'){
    $idProduto = $_GET['id'];
    $_SESSION['itens'][$idProduto] -= 1;
    if ($_SESSION['itens'][$idProduto == 0]){
        unset($_SESSION['itens'][$idProduto]);
    }
    echo '<meta HTTP-EQUIV="REFRESH" CONTENT="0; URL=sistema.php?p=cardapio"/>'; 
}

echo "</div>";

?>

Belê? If you need some other part of code, just say so. But that’s it, I really want to understand this stop rsrsrs so any comment that contributes to a better understanding of this issue will help me a lot.. Grateful to all NATION! ^^

  • 1

    Hello Lougans, the add is duplicating because only in remove you redirect the user to a url without the _GET variables. My suggestion: put everything at the beginning of PHP, add and remove. In both cases you manipulate the _SESSION variable and then redirect the user. But try using header('Location:') instead of html <meta tag>

  • Whoa, bro.. Your comment was very helpful, I’ll follow your tip! vlwww

No answers

Browser other questions tagged

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