Problems in PHP cart

Asked

Viewed 31 times

0

It follows the code of my cart. I wanted it not to repeat the products but add up the amount of them in the cart. I’m having a hard time with this part.

<?php
include 'conexao.php';
session_start();
$_SESSION['carrinho'][] = $_GET['produtoid'];
?>

<head>

<style type="text/css">
    table, tr, td{
        border: 1px solid rgba(0,0,0,0.2);
    }

</style>

<table>

    <tr>

        <td>Nome</td>

        <td>Quantidade</td>

        <td>Subtotal</td>

    </tr>


    <?php

         for($i = 0; $i < count($_SESSION['carrinho']); $i++){

        $consulta = "SELECT * FROM produto where id =".$_SESSION['carrinho'][$i]." ";

         $resultado = $PDO->query($consulta); 

         $vetorResultado = $resultado->fetchAll(PDO::FETCH_ASSOC);

         foreach ($vetorResultado as $valor) {

            echo "<tr><td>".$valor['nome']."</td>";
            echo "<td><input type='text' size='3' name='vetorResultado['id']' value='1'></td>";
            echo "<td>".$valor['preco']."</td></tr>";
      }







    }


    ?>

</table> 

Finalize purchase
Keep buying

1 answer

0

Good afternoon Leonardo, as you are storing this data in the database you can change your query a little and return the quantity of products grouping the records.

$consulta = "SELECT nome,preco,count(nome) as qtd FROM produto where id =".$_SESSION['carrinho'][$i]." group by nome,preco";

This query will return you nome, preco and qtd (number of grouped lines). Ai then just change your loop.

foreach ($vetorResultado as $valor) {
    echo "<tr><td>".$valor['nome']."</td>";
    echo "<td><input type='text' size='3' name='vetorResultado['id']' value='".$valor['qtd']."'></td>";
    echo "<td>".$valor['preco']."</td></tr>";
}

Try this.

Browser other questions tagged

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