Insert, sum and display value (in real) using PHP and MySQL [duplicate]

0
Hello, I am a beginner in PHP and MySQL. I would like to have a form where I enter a value (in real, in the case), add with what you have already saved in the database, and finally display to the user the result of this calculation.

It's quite simple, just for study.

I have a form and a table in the database with a field of type DECIMAL. I can already save in the database, but if I type in the input a value of type "1,280.90", in my database it saves only as "1":

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jJulius</title>
</head>
<body>

    <?php
    $servername = "localhost";
    $database = "jjulius";
    $username = "root";
    $password = "";

    // Create connection
    $conn = mysqli_connect($servername, $username, $password, $database);

    // Check connection
    if (!$conn) {

        die("Connection failed: " . mysqli_connect_error());

    }
    echo "Connected successfully";
    ?>

    <?php
    if(isset($_POST['save']))
    {
        $valor=$_POST['valor'];


        $sql = "INSERT INTO valor (valor) VALUES ";
        $sql .= "('$valor')"; 
        mysqli_query($conn,$sql) or die("Erro ao tentar cadastrar registro");
        mysqli_close($conn);

    }

    ?>

    <form action="" method="post">
        <input type="text" name="valor" />
        <button type="submit" name="save">Enviar</button>
    </form>

</body>
</html>

Can anyone help me with how to save and display this data correctly, please?

Thank you in advance. :)

    
asked by anonymous 23.06.2018 / 01:47

1 answer

0

First, the DECIMAL field of MySql requires exact precision, by my choice I use FLOAT .

Then the value to be saved must contain at most a . separating the decimals, 1234.56 for example, so you need to keep only the numbers and replace , with . .

The preg_replace () function retains only numbers and a comma: / p>

$valor=preg_replace("/[^0-9,]+/i","",$_POST["valor"]);

The function str_replace () , here, replaces the comma with the end point:

$valor=str_replace(",",".",$valor);

Performs INSERT :

$sql = "INSERT INTO valor (valor) VALUES ('$valor')"; 
mysqli_query($conn,$sql) or die("Erro ao tentar cadastrar registro");

Performs SELECT , using CONCAT to add the R$ to the result, and COUNT to sum the values:

$sql = "SELECT CONCAT('R$ ', SUM(valor)) AS total FROM valor";

if($result = mysqli_query($conn,$sql)):
    while($row = mysqli_fetch_assoc($result)):
        echo "Total: ".$row["total"];
    endwhile;
    mysqli_free_result($result);
endif;
    
23.06.2018 / 04:42