How to format numeric data extracted from the database for monetary values?

0

I am using the jquery.maskMoney.js library to format system monetary data. But when the data is saved in the database and returned to the system screen the formatting is lost. How to solve this problem? I would like the formatting to remain, follow some screens of the system that exemplify this problem.

1. Data with currency formatting: entering data into forms

2.Non-monetarydata:Databeingloadedfromthedatabase 3.Codesnippetoftheedita.blade.phppage

<divclass="col-md-5 form-group">
<label class="control-label">Valor Solicitado (R$)</label>

<input type="text" class="form-control"  id="vlSolicitado" name="vlSolicitado" value="{{str_replace('.',',',$projeto->valor_solicitado)}}" data-thousands="." data-decimal="," data-prefix="R$ " maxlength="18"  required>  
</div>


4. Database Query Result

    
asked by anonymous 27.08.2018 / 17:01

2 answers

2

I'll guide you to handle the data before inserting it into the database.

  • I assume you are using PHP to handle the information before inserting it into the database ( MySQL ). >

  • I also assume that your database is properly structured to receive information from your forms.

  • For monetary values the field must be of type DECIMAL (7,2) , two digits after the dot and I believe that 7 digits before the dot is sufficient.

    As you are formatting the value with a Jquery mask, as soon as you pass the value to PHP, they also come in formatted. Example: 2,000.00.

    You need to delete this formatting, because your database will not accept the characters: "." and "," thereby generating an error.

    If the form values are being sent via POST , do so:

    // Valor recebido do formulário, campo valor solicitado (2.000,00)
    $valor = $_POST['valorSolicitado'];
    
    // Removo da variável o "."
    $valor = str_replace('.' '', $valor);
    // Substituo a "," pelo "." pois é esse formato que o campo do seu banco de dados vai aceitar
    $valor = str_replace(',' '.', $valor);
    
    // Esta variável irá imprimir:
    // 2000.00
    

    When you retrieve the value from your database, format it using a PHP function called number_format :

    // Valor recuperado do banco de dados (2000.00)
    $valor = $valor_do_banco_de_dados;
    
    $valor = number_format($valor, 2, ',', '.');
    
    // Esta variável irá imprimir:
    // 2.000,00
    
        
    27.08.2018 / 19:09
    0

    Hello @Ruama, try to make an explode with php in the value obtained by the select from bd, before displaying it in the form. For example:

    $sql = "SELECT * FROM TABELA WHERE id=$id_escolhido";
    $rs = mysqli_query($con, $sql);
    
    while ($row= mysqli_fetch_array($rs)){
       $valor = $row['valor'];
       $valor_explode = explode(",", $valor);
    }
    
        
    27.08.2018 / 18:45