Ir para conteúdo
Fórum Script Brasil
  • 0

Mensagem de erro ao voltar página


Edu Valente

Pergunta

Boa tarde. Eu tenho um arquivo php que valida a entrada do usuário quando este insere a quant. de anos de investimento. Quando o usuário não insere a quant. de anos correta, é impressa a mensagem "years is a required field". Esta mensagem aparece quando eu insiro um número para "years", clico para enviar e volto a esta página. Gostaria de fazer com que a mensagem desaparecesse ao retornar à página inicial. Já tentei fazer isso inicializando novamente o valor de $error_message mas não deu certo.

<?php
  // variables initialization
  if(empty($_POST['years']))
  {
     $years = 0;  
  }
  else {
     $years = $_POST['years'];   
  }
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Future Value Calculator</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
</head>

<body>
    <div id="content">
    <h1>Future Value Calculator</h1>
    <?php if (!empty($error_message)) { ?>
        <p class="error"><?php echo $error_message; ?></p>
    <?php } // end if ?>
    <form action="display_results.php" method="post">

        <div id="data">
            <label>Investment Amount:</label>
            <select name = "investment" id = "investment">
              <?php 
                for($i = 10000; $i <= 50000; $i += 10000)
                {
              ?>
                <option value = "<?php echo $i; ?>">$<?php echo $i; ?></option>
              <?php
                }
              ?>    
            </select>
            
            <label>Interest Rate:</label>
            <select name = "interest_rate" id = "interest_rate">
              <?php 
                for($i = 4; $i <= 12; $i += .5)
                {
              ?>
                <option value = "<?php echo $i; ?>"><?php echo $i; ?>%</option>
              <?php
                }
              ?>    
            </select>
            
            <label>Number of Years:</label>
            <input type="text" name="years"
                   value="<?php echo $years; ?>"/><br />
            
            
            <!--
            <label>Investment Amount:</label>
            <input type="text" name="investment"
                   value=" "/><br /> 

            <label>Yearly Interest Rate:</label>
            <input type="text" name="interest_rate"
                   value=" "/><br />
            -->
        </div>

        <div id="buttons">
            <label> </label>
            <input type="submit" value="Calculate"/><br />
        </div>

    </form>
    </div>
</body>
</html>
<?php
    // get the data from the form
    $investment = $_POST['investment'];
    $interest_rate = $_POST['interest_rate'];
    $years = $_POST['years'];

    // validate investment entry
    
    // these statements work incorrectly with a drop-list
    /*
    if ( empty($investment) ) {
        $error_message = 'Investment is a required field.'; 
    } else if ( !is_numeric($investment) )  {
        $error_message = 'Investment must be a valid number.'; 
    } else if ( $investment <= 0 ) {
        $error_message = 'Investment must be greater than zero.';        
    // validate interest rate entry
    } else if ( empty($interest_rate) ) {
        $error_message = 'Interest rate is a required field.'; 
    } else if ( !is_numeric($interest_rate) )  {
        $error_message = 'Interest rate must be a valid number.'; 
    } else if ( $interest_rate <= 0 ) {
        $error_message = 'Interest rate must be greater than zero.';        
    // set error message to empty string if no invalid entries
    */
    if(!is_numeric($years))
    {
       $error_message = 'Years must be a valid number';
    }
    else if(empty($years))
    {
       $error_message = 'Years is a required field';    
    }
    else { 
        $error_message = '';
    }
    
    // if an error message exists, go to the index page
    if ($error_message != '') {
        include('index.php');
        exit();
    }

    // calculate the future value
    $future_value = $investment;
    for ($i = 1; $i <= $years; $i++) {
        $future_value = ($future_value + ($future_value * $interest_rate *.01));
    }

    // apply currency and percent formatting
    $investment_f = '$'.number_format($investment, 2);
    $yearly_rate_f = $interest_rate.'%';
    $future_value_f = '$'.number_format($future_value, 2);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Future Value Calculator</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
</head>
<body>
    <div id="content">
        <h1>Future Value Calculator</h1>

        <label>Investment Amount:</label>
        <span><?php echo $investment_f; ?></span><br />

        <label>Yearly Interest Rate:</label>
        <span><?php echo $yearly_rate_f; ?></span><br />

        <label>Number of Years:</label>
        <span><?php echo $years; ?></span><br />

        <label>Future Value:</label>
        <span><?php echo $future_value_f; ?></span><br />
    </div>
</body>
</html>

Link para o comentário
Compartilhar em outros sites

2 respostass a esta questão

Posts Recomendados

  • 0
Boa tarde. Eu tenho um arquivo php que valida a entrada do usuário quando este insere a quant. de anos de investimento. Quando o usuário não insere a quant. de anos correta, é impressa a mensagem "years is a required field". Esta mensagem aparece quando eu insiro um número para "years", clico para enviar e volto a esta página. Gostaria de fazer com que a mensagem desaparecesse ao retornar à página inicial. Já tentei fazer isso inicializando novamente o valor de $error_message mas não deu certo.

<?php
  // variables initialization
  if(empty($_POST['years']))
  {
     $years = 0;  
  }
  else {
     $years = $_POST['years'];   
  }
?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Future Value Calculator</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
</head>

<body>
    <div id="content">
    <h1>Future Value Calculator</h1>
    <?php if (!empty($error_message)) { ?>
        <p class="error"><?php echo $error_message; ?></p>
    <?php } // end if ?>
    <form action="display_results.php" method="post">

        <div id="data">
            <label>Investment Amount:</label>
            <select name = "investment" id = "investment">
              <?php 
                for($i = 10000; $i <= 50000; $i += 10000)
                {
              ?>
                <option value = "<?php echo $i; ?>">$<?php echo $i; ?></option>
              <?php
                }
              ?>    
            </select>
            
            <label>Interest Rate:</label>
            <select name = "interest_rate" id = "interest_rate">
              <?php 
                for($i = 4; $i <= 12; $i += .5)
                {
              ?>
                <option value = "<?php echo $i; ?>"><?php echo $i; ?>%</option>
              <?php
                }
              ?>    
            </select>
            
            <label>Number of Years:</label>
            <input type="text" name="years"
                   value="<?php echo $years; ?>"/><br />
            
            
            <!--
            <label>Investment Amount:</label>
            <input type="text" name="investment"
                   value=" "/><br /> 

            <label>Yearly Interest Rate:</label>
            <input type="text" name="interest_rate"
                   value=" "/><br />
            -->
        </div>

        <div id="buttons">
            <label> </label>
            <input type="submit" value="Calculate"/><br />
        </div>

    </form>
    </div>
</body>
</html>
<?php
    // get the data from the form
    $investment = $_POST['investment'];
    $interest_rate = $_POST['interest_rate'];
    $years = $_POST['years'];

    // validate investment entry
    
    // these statements work incorrectly with a drop-list
    /*
    if ( empty($investment) ) {
        $error_message = 'Investment is a required field.'; 
    } else if ( !is_numeric($investment) )  {
        $error_message = 'Investment must be a valid number.'; 
    } else if ( $investment <= 0 ) {
        $error_message = 'Investment must be greater than zero.';        
    // validate interest rate entry
    } else if ( empty($interest_rate) ) {
        $error_message = 'Interest rate is a required field.'; 
    } else if ( !is_numeric($interest_rate) )  {
        $error_message = 'Interest rate must be a valid number.'; 
    } else if ( $interest_rate <= 0 ) {
        $error_message = 'Interest rate must be greater than zero.';        
    // set error message to empty string if no invalid entries
    */
    if(!is_numeric($years))
    {
       $error_message = 'Years must be a valid number';
    }
    else if(empty($years))
    {
       $error_message = 'Years is a required field';    
    }
    else { 
        $error_message = '';
    }
    
    // if an error message exists, go to the index page
    if ($error_message != '') {
        include('index.php');
        exit();
    }

    // calculate the future value
    $future_value = $investment;
    for ($i = 1; $i <= $years; $i++) {
        $future_value = ($future_value + ($future_value * $interest_rate *.01));
    }

    // apply currency and percent formatting
    $investment_f = '$'.number_format($investment, 2);
    $yearly_rate_f = $interest_rate.'%';
    $future_value_f = '$'.number_format($future_value, 2);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Future Value Calculator</title>
    <link rel="stylesheet" type="text/css" href="main.css"/>
</head>
<body>
    <div id="content">
        <h1>Future Value Calculator</h1>

        <label>Investment Amount:</label>
        <span><?php echo $investment_f; ?></span><br />

        <label>Yearly Interest Rate:</label>
        <span><?php echo $yearly_rate_f; ?></span><br />

        <label>Number of Years:</label>
        <span><?php echo $years; ?></span><br />

        <label>Future Value:</label>
        <span><?php echo $future_value_f; ?></span><br />
    </div>
</body>
</html>
faça o seguinte, onde estive esse trecho apague tudo
<?php
  // variables initialization
  if(empty($_POST['years']))
  {
     $years = 0;  
  }
  else {
     $years = $_POST['years'];   
  }
?>
e troque por esse trecho.
<?php
( empty($_POST['years']) ) ? ($years=23) : ($years=$_POST['years']);
?>

agora a variavel $years sempre conterá dados, e assim não exibirar até mensagem chata, mas não sei se o funcionamento do sistema será o mesmo.

teste e coloque a resposta até mais.

Link para o comentário
Compartilhar em outros sites

  • 0
faça o seguinte, onde estive esse trecho apague tudo

<?php
  // variables initialization
  if(empty($_POST['years']))
  {
     $years = 0;  
  }
  else {
     $years = $_POST['years'];   
  }
?>
e troque por esse trecho.
<?php
( empty($_POST['years']) ) ? ($years=23) : ($years=$_POST['years']);
?>

agora a variavel $years sempre conterá dados, e assim não exibirar até mensagem chata, mas não sei se o funcionamento do sistema será o mesmo.

teste e coloque a resposta até mais.

Com a sua ajuda percebi que eu estava me contradizendo. O que estava ocorrendo era um erro de lógica. Eu fiz uma verificação com empty no código do display_results e empty retorna true se o valor for zero, '', false ou nul então a mensagem de erro sempre aparecerá se eu atribuir 0 a $years. Conclusão: inicializar a variável com 0 e testá-la com empty nunca vai dar certo :P Obrigado.

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,1k
    • Posts
      651,8k
×
×
  • Criar Novo...