calculation with BD data, bring service, value and total

Asked

Viewed 53 times

0

I need to save cliente, serviço, valor of a service. The first problem is to be able to return the total value (the sum of the services).

Man form until the moment is like this:

<form action="valortotal.php" method="post">
    <div class="form-group">
        <label for="autocomplete" class="col-sm-2 control-label">Cliente: </label>
        <div class="col-sm-4">
            <input id="autocomplete">
        </div>
    </div>
    <br><br>

    <div class="form-group">
        <label for="inputEmail3" class="col-sm-2 control-label">Serviços: </label>
        <div class="col-sm-4">
            <?php
            $query_servicos = "SELECT * FROM servicos ORDER BY nome ASC";
            $result_servicos = mysqli_query($conectar, $query_servicos);
            while ($linhas_servicos = mysqli_fetch_assoc($result_servicos)) {
                echo " <input type=checkbox name='nomes[]' value=" . $linhas_servicos['preco'] . "> " . $linhas_servicos['nome'] . "<br>";
            }
            ?>
        </div>
    </div>
    <br>

    <input type=submit>
</form>

Content of.php total value:

<?php
// Verifica se usuário escolheu algum número
if (isset($_POST["nomes"])) {
    echo "Os números de sua preferência são:<BR>";

    // Faz loop pelo array dos numeros
    foreach ($_POST["nomes"] as $nomes) {
        echo $nomes + $nomes . "<BR>";
    }
}

It is adding up individually. How do I get the total sum ?

  • Ronaldo, welcome. I know that wasn’t your question, but there’s something very wrong with your code. You shouldn’t put the database search in the middle of your html. Ideally, you should separate that responsibility into another class. That could get you in trouble in the future.

1 answer

1


It took little to arrive at the right answer... You must define a variable to make the sum of the data you want... I would do so:

<?php
// Verifica se usuário escolheu algum número
if (isset($_POST["nomes"])) {
    echo "Os números de sua preferência são:<BR>";

    $totalServicos = 0;
    // Faz loop pelo array dos numeros
    foreach ($_POST["nomes"] as $nomes) {
        $totalServicos += $nomes;
    }

    echo "R$ ".number_format($totalServicos, 2, ',', '.');
}

Browser other questions tagged

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