Total in shopping cart

Asked

Viewed 330 times

2

I’m having trouble with the cart, if I put $preço =$linha['preço']; displays the value correctly, but if I put the number_format below, it Zera the result:

$preço = number_format((float) $linha['preço'] * $qtd, 2, ',', '.');

And the total products are not being made, I was told that have to use javascript , but I do not know javascript, someone can help?

<?php
include(dirname(__FILE__) . './funcao/conecta.php');
session_start();

if (!isset($_SESSION['shop'])) {
    $_SESSION['shop'] = array();
}

if (isset($_GET['acao'])) { // adicionar produto
    $id = isset($_GET['id']) ? intval($_GET['id']) : null;
    if ($_GET['acao'] == 'add') {
        if (!isset($_SESSION['shop'][$id])) {
            $_SESSION['shop'][$id] = 1;
        }
    } elseif ($_GET['acao'] == 'del') {  //REMOVER shop
        if (isset($_SESSION['shop'][$id])) {
            unset($_SESSION['shop'][$id]);
        }
    }

//ALTERAR QUANTIDADE
    //Se existir $_POST['prod'] então começa..
    if (isset($_POST['prod']))
        if ($_GET['acao'] == 'atualizar') {
            if (is_array($_POST['prod'])) {
                foreach ($_POST['prod'] as $id => $qtd) {
                    $id = intval($id);
                    $qtd = intval($qtd);
                    if (!empty($qtd) || $qtd <> 0) {
                        $_SESSION['shop'][$id] = $qtd;
                    } else {
                        unset($_SESSION['shop'][$id]);
                    }
                }
            }
        }
}
?>

HTML:

<!doctype html>
<html>
    <head>
        <meta charset='utf8'>
        <title>Seja Bem Vindo!</title>
        <link rel="stylesheet" href="css/default.css">
    </head>
    <body>
        <div><h2>Suas Compras Efetuadas:</h2>
            <br>
            <table border="1" width="100%">
                <thead>
                    <tr>
                        <th width="10%">FOTO</th>
                        <th width="10%">NOME</th>
                        <th width="10%">DESCRIÇÃO</th>
                        <th width="10%">TAMANHO</th>
                        <th width="10%">COR</th>
                        <th width="10%">PREÇO</th>
                        <th width="10%">QTD.</th>
                        <th width="10%">SUBTOTAL</th>
                        <th width="10%">REMOVER</th>
                    </tr>
                </thead>
                <tr><td colspan="9">
                        <form action="?acao=atualizar" method="post">
                            <table><tfoot>
                                    <tr>
                                        <td><input type="submit" value="Atualizar"></td>
                                    </tr><tr>
                                        <td><a href="./index.php">Continuar Comprando</a></td>
                                    </tr><tr>
                                        <td><a href="./admin/finalizar.php">Finalizar Pedido</a></td>
                                </tfoot></table>
                        </form>
                    </td></tr>
                <tbody>
                    <?php
                    $total = 0;
                    if (count($_SESSION['shop']) == 0) {
                        echo '<tr><td colspan="9"><div class="#">O cesto de compras esta vazio!</td></tr>';
                    } else {
                        $conn = new PDO("mysql:host=localhost;dbname=loja", "root", "");
                        foreach ($_SESSION['shop'] as $id => $qtd) {
                            $cart = $conn->prepare("SELECT * FROM produtos WHERE  id=$id");
                            $cart->setFetchMode(PDO::FETCH_ASSOC);
                            $cart->execute();
                            while ($linha = $cart->fetch()) {
                                $foto = $linha['foto'];
                                $nome = $linha['nome'];
                                $descricao = $linha['descricao'];
                                $tamanho = $linha['tamanho'];
                                $cor = $linha['cor'];




                              $preço = number_format((float) $linha['preço'] * $qtd, 2, ',', '.');
                              $sub = number_format((float) $linha['preço'] * $qtd, 2, ',', '.');
                                $sub =  $linha['preço'] * $qtd;
                                $total += $preço;
                                $total = number_format($total, 2, ',', '.');
                                echo '<tr>
                                             <td><img src = "' . $foto . ' " width = "100px"</td>
                                             <td>' . $nome . '</td>
                                             <td>' . $descricao . '</td>
                                             <td>' . $tamanho . '</td>
                                             <td>' . $cor . '</td>

                                             <td>R$ ' . $preço . '</td>
                                             <td><input type="text" size="3" name="prod[' . $id . ']" value="' . $qtd . '" /></td>
                                             <td>R$ ' . $sub . '</td>
                                             <td colspan = "9"><a href="?acao=del&id=' . $id . '"><img src="./imagens/remover.png" width="70" height="70" ></td>
                                             </tr>';
                            }
                        }
                    }
                    ?>
            </table>
        </div>
    </body>
</html>

1 answer

1

Dude, I ran a test on your code using the website http://phptester.net/ and worked normally.

Obs:

1 - In good practice programming never use special characters such as "ç" in variables

2- Before concatenating, check that the variable is declared before... in the "$total += $price;" first of all put "$total=0;"

3 - Use floatval to convert the values "floatval($line['price'])" and make sure the user is using "." instead of "," otherwise use replace in variable.

<?php
$linha = Array();
$linha['preco'] = "5,5";
$linha['preco'] = str_replace(",",".",$linha['preco']);
$total =0; 
$qtd =3;
$preco = number_format(floatval($linha['preco']) * $qtd, 2, ',', '.');
$sub =  $linha['preco'] * $qtd;
$total += $preco;
echo '
<p>com o number_format: R$ ' . $preco . '</p>
<p>sem o number_format: R$ ' . $sub . '</p>';
 ?>

Browser other questions tagged

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