Change . by , with PHP or Mysql

Asked

Viewed 430 times

2

I have a table that saves data that comes from a txt and I have a value field and it saves in format: 5.00

How do I change in the database or PHP to 5,00?

That is, changing the . (point) by , (comma).

Code:

<?php
include 'includes\head.php';
include "conexao.php";
  $data_mes = $_POST['mes'];
  $data_ano = $_POST['ano'];
// Pasta onde o arquivo vai ser salvo
$_UP['pasta'] = 'uploads/';
// Tamanho máximo do arquivo (em Bytes)
$_UP['tamanho'] = 1024 * 1024 * 4; // 2Mb
// Array com as extensões permitidas
$_UP['extensoes'] = array('jpg', 'png', 'gif','txt','pdf');
// Renomeia o arquivo? (Se true, o arquivo será salvo como .jpg e um nome único)
$_UP['renomeia'] = true;
// Array com os tipos de erros de upload do PHP
$_UP['erros'][0] = 'Não houve erro';
$_UP['erros'][1] = 'O arquivo no upload é maior do que o limite do PHP';
$_UP['erros'][2] = 'O arquivo ultrapassa o limite de tamanho especifiado no HTML';
$_UP['erros'][3] = 'O upload do arquivo foi feito parcialmente';
$_UP['erros'][4] = 'Não foi feito o upload do arquivo';
// Verifica se houve algum erro com o upload. Se sim, exibe a mensagem do erro
if ($_FILES['arquivo']['error'] != 0) {
  die("Não foi possível fazer o upload, erro:" . $_UP['erros'][$_FILES['arquivo']['error']]);
  exit; // Para a execução do script
}
// Caso script chegue a esse ponto, não houve erro com o upload e o PHP pode continuar
// Faz a verificação da extensão do arquivo
$extensao = strtolower(end(explode('.', $_FILES['arquivo']['name'])));
if (array_search($extensao, $_UP['extensoes']) === false) {
  echo "Por favor, envie arquivos com as seguintes extensões: txt,pdf,jpg, png ou gif";
  exit;
}
// Faz a verificação do tamanho do arquivo
if ($_UP['tamanho'] < $_FILES['arquivo']['size']) {
  echo "O arquivo enviado é muito grande, envie arquivos de até 2Mb.";
  exit;
}
// O arquivo passou em todas as verificações, hora de tentar movê-lo para a pasta
// Primeiro verifica se deve trocar o nome do arquivo
if ($_UP['renomeia'] == true) {
  // Cria um nome baseado no UNIX TIMESTAMP atual e com extensão .jpg
  $nome_final = 'tefonia.txt';
  //$nome_final = md5(time()).'.txt';
} else {
  // Mantém o nome original do arquivo
  $nome_final = $_FILES['arquivo']['name'];
}


// Depois verifica se é possível mover o arquivo para a pasta escolhida
if (move_uploaded_file($_FILES['arquivo']['tmp_name'], $_UP['pasta'] . $nome_final)) {
  // Upload efetuado com sucesso, exibe uma mensagem e um link para o arquivo
 echo "<center><h1>Upload efetuado com sucesso! <br></h1>";
 echo '<div align="center">';
 echo '<img src="images\logo.jpg">';
 echo '</div>';
 echo '<br><a href="uploadtxt.php" class="btn btn-primary">Voltar</a></center>';
} else {
  // Não foi possível fazer o upload, provavelmente a pasta está incorreta
  echo "Não foi possível enviar o arquivo, tente novamente";
}

$filename = "uploads/tefonia.txt";
$arq = fopen ($filename, "r");
$read = fread ($arq, filesize ($filename) );

$separador = ";"; // O que separa os resultados no arquivos TXT ?

$array = explode($separador, $read);
$conta = count($array);

for ($i=0; $i < $conta; $i++) {

    $sql_conta = "INSERT INTO contas_txt (contas_txt_id, contas_txt_nome, contas_txt_celular, contas_txt_data,
                contas_txt_hora, contas_txt_desc, contas_txt_cod, contas_txt_fixo,
                contas_txt_tel_dest, contas_txt_minutos, contas_txt_vazio1, contas_txt_vazio2, contas_txt_valor,contas_txt_mes,contas_txt_ano) 
                VALUES (NULL, '" . $array[$i] . "', '" . @$array[$i + 1] . "', '" . @$array[$i + 2] . "',
                    '" . @$array[$i + 3] . "', '" . @$array[$i + 4] . "', '" . @$array[$i + 5] . "',
                    '" . @$array[$i + 6] . "', '" . @$array[$i + 7] . "', '" . @$array[$i + 8] . "',
                    '" . @$array[$i + 9] . "', '" . @$array[$i + 10] . "', '" . @$array[$i + 11] . "', '".$data_mes. "', '".$data_ano."')";
   $resultado_conta = mysql_query($sql_conta) 
    or die(mysql_error());

   $sql_valor = "UPDATE contas_txt SET contas_txt_valor = replace( contas_txt_valor, '.', ',' )";
              $resultado_replace = mysql_query($sql_valor) 
              or die(mysql_error());


 //  $sql_celular = "INSERT INTO celular (id,celular) VALUES (NULL,'" . @$array[$i + 1] . "')";
 //  $resultado_celular = mysql_query($sql_celular) 
 //    or die(mysql_error());



    $i = $i + 11;


} 

mysql_close();
  • 3

    Do not change in the bank. Either save to the bank with the DECIMAL type, or multiply by 100 and save as INT. When it comes to displaying, exchange the dots for a comma, with str_replace, in PHP.

  • I did not understand well, follows my code. Where would do this multiplication ?

  • @bfavaretto because it could not save in FLOAT?

  • 1

    @Inkeliz Power, you can, but you take your chances cause accuracy problems.

  • @bfavaretto did not know this difference. :| Is there any way to convert from float to decimal (keeping same value), or is path without return?

  • @Inkeliz If you only store and have a few decimal places, usually standard rounding solves you. But when you start to group data and make calculations, the error accumulates. But it depends a lot on what you need to do, it is important to avoid floats especially when dealing with coins. http://sqlfiddle.com/#! 9/006e5/2

  • Otacio, it is simpler to set the column as decimal in the bank.

  • I did a quick search around here. Sorry to 'mess up' the topic with a 'nothing' subject. In this case I do not use the data to perform sum/subtraction, only to order and display them. Now there is some performance problem in it (vs decimal), even using index?

  • Otacio, please do not undo the improvements that other users make to your post (formatting, grammar and removing greetings). If you want to know more about the wiki model of [en.so] can check the [tour]. Thank you!

Show 4 more comments

1 answer

6


  • Thank you for the explanation.

Browser other questions tagged

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