I need to receive data in PHP page and keep the page running

Asked

Viewed 143 times

-3

I’m having difficulties in web development work, which asks for the following:

1 - Build a page that draws an integer number from 1 to 10 and ask the user what is the "imagined".
2 - Your page shall indicate whether the attempt made by the user is greater or less that the number drawn and count the number of attempts.
3 - When the user gets the number right the program should classify the user as:
-> 1 try: very lucky;
-> From 2 to 3 attempts: lucky;
-> From 4 to 5 attempts: normal;
-> More than 5 attempts: below average;

The code I made is this:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">

    <title>Atividade 8 Slide 9</title>      
</head>
<body>  

    <div>

        <form method="get" action="atividade9.php">
            <fieldset>
                <legend>Atividade 9</legend>
                <label for="txt" accesskey="1">Nº imaginado</label>
                <input type="number" id="int" name="a" placeholder="Digite aqui o número"/>
                <button type="submit">Enviar</button>
            </fieldset>         
        </form>

        <?php 

            session_start();
            if($_SESSION[1] == null || $_SESSION[2] == null)
            {
                echo 'ativando session';
                $_SESSION[1] = 1;
                $_SESSION[2] = rand(1, 10);
            }

            $i = $_SESSION[1];
            $b = $_SESSION[2];

            if (isset($_GET['a'])) {
                $a = $_GET['a'];
            }

            if ($a == $b) {
                if ($i == 1) {
                    echo '<p>muito sortudo</p>';
                }
                else if ($i < 3) {
                    echo '<p>sortudo</p>';  
                }
                else if ($i < 5) {
                    echo '<p>normal</p>';
                }
                else {
                    echo '<p>abaixo da médio</p>';
                }
                session_destroy();
            } 
            else if ($a > $b){
                echo '<p>Maior que o número</p>';
                $i++;
                echo '<p>I = '. $i .' B = '. $b .'</p>';
                $_SESSION[1] = $i;  
            } 
            else if ($a < $b) {
                echo '<p>Menor que o número</p>';
                $i++;
                echo '<p>I = '. $i .' B = '. $b .'</p>';
                $_SESSION[1] = $i;
            }                               
        ?>

    </div>
</body>
</html>

The page can only use php and html, and even using Session I couldn’t get the variables to keep the value every time the user tries.

  • Hello Pedro! I see you are a young programmer. Good! It got a little confusing for us to understand what you want to do with the "a" field, or with Session['2'], etc. Try to use some clearer variables and explain what logic you are using. So we can say if it is a good logic and give suggestions on how to improve the code.

  • Thanks for the tips, is that I have little/no experience with php. I have to admit that even I didn’t know what I wanted besides persistence of the data received on page for action in itself and that could only be used php.

2 answers

2

Look I recommend you take a good look at : How to ask a good question

But as you are learning I commented all the code, I hope you read, understand and redo the code for better learning.

<?php
// Inicia a sessão
    session_start();

// Verifica se existe um POST   
    if(isset($_POST['enviar']))
    {
        // Verifica se existe a tentativas  
            if(isset($_SESSION['tentativas']) && isset($_SESSION['sorteado']))
            {
                // Recupera os dados
                    $tentativas = $_SESSION['tentativas'];
                    $_SESSION['tentativas']++;
                    $sorteado   = $_SESSION['sorteado'];
            }else
            {
                // Cria a sessão tentativas & sessão sorteado
                    $_SESSION['tentativas'] = 1;
                    $_SESSION['sorteado']   = rand(1,10);

                    $tentativas = $_SESSION['tentativas'];
                    $sorteado   = $_SESSION['sorteado'];
            }

        // Pegando número digitado
            $numero  = addslashes($_POST['numero']);

        // Fazendo as verificações
            if( ($numero) == $sorteado )
            {
                // Verifica o número de tentativas
                    if( ($tentativas) == 1 )
                    {
                        // Exibe mensagem
                            echo "Você acertou em  ".$tentativas." tentativa(s);<br />";
                            echo "Nível de tentativa: Muito sortudo(a)";

                        // Destroi as sessões   
                            session_destroy();

                    }elseif( ($tentativas) > 1 && $tentativas < 4 )
                    {
                        // Exibe mensagem
                            echo "Você acertou em  ".$tentativas." tentativa(s);<br />";
                            echo "Nível de tentativa: Sortudo(a)";

                        // Destroi as sessões
                            session_destroy();

                    }elseif( ($tentativas) > 3 && $tentativas < 6 )
                    {
                        // Exibe mensagem
                            echo "Você acertou em  ".$tentativas." tentativa(s);<br />";
                            echo "Nível de tentativa: Normal";

                        // Destroi as sessões
                            session_destroy();

                    }elseif( ($tentativas) > 5 )
                    {
                        // Exibe mensagem
                            echo "Você acertou em  ".$tentativas." tentativa(s);<br />";
                            echo "Nível de tentativa: Abaixo da média";

                        // Destroi as sessões
                            session_destroy();
                    }

            }elseif( ($numero) > $sorteado ) 
            {
                // Exibe mensagem
                    echo "Tente um número menor <br />";
                    echo "Tentativa número ".$tentativas."<br />";

            }elseif( ($numero) < $sorteado )
            {
                // Exibe mensagem
                    echo "Tente um número maior <br />";
                    echo "Tentativa número ".$tentativas."<br />";
            }
    }
?>
<!DOCTYPE HTML><html>
<head>
    <title>Tentativas</title>
</head>

<body>

    <!--Formulário-->
        <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
            Qual número sorteado ? <input type="number" name="numero" /> 
            <input type="submit" name="enviar" value="Enviar" />
        </form>
    <!--// Formulário-->

</body>

Note: Want nothing "chewed" because then there will be no learning for yourself, just open is "exception" because I found the idea intriguing.

1


Note: The session_start() function should be the first line in your document. Before any HTML tags The session name cannot consist only of digits, at least one letter must be present. Otherwise a new session id is generated every time.

<?php 
session_start();

if($_SESSION["s1"] == null || $_SESSION["s2"] == null)
{

 $_SESSION["s1"] = 1;
 $_SESSION["s2"] = rand(1, 10);

 echo 'ativando session';

}

$i = $_SESSION["s1"];
$b = $_SESSION["s2"];

if (isset($_GET['a'])) {
  $a = $_GET['a'];

  if ($a == $b) {
    if ($i == 1) {
      echo '<p>muito sortudo</p>';
    }
    else if ($i < 3) {
      echo '<p>sortudo</p>'; 
    }
    else if ($i < 5) {
      echo '<p>normal</p>';
    }
    else {
       echo '<p>abaixo da m&eacute;dia</p>';
    }
    session_unset();
    session_destroy();
  } 
  else if ($a > $b){
    echo '<p>Maior que o n&uacute;mero</p>';
    $i++;
     echo '<p>I = '. $i .' B = '. $b .'</p>';
     $_SESSION["s1"] = $i; 
  } 
  else if ($a < $b) {
     echo '<p>Menor que o n&uacute;mero</p>';
     $i++;
     echo '<p>I = '. $i .' B = '. $b .'</p>';
     $_SESSION["s1"] = $i;
   } 

} 
?>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Atividade 8 Slide 9</title> 
</head>
<body> 

<div>

<form method="get" action="atividade9.php">
<fieldset>
<legend>Atividade 9</legend>
<label for="txt" accesskey="1">N&ordm; imaginado</label>
<input type="number" id="int" name="a" placeholder="Digite aqui o n&uacute;mero"/>
<button type="submit">Enviar</button>
</fieldset> 
</form>

</div>
</body>
</html>

Browser other questions tagged

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