skip to Main Content

I wrote this code in PHP to present the message if I entered any random number between 1 and 100, but when I submit the value, it doesn’t display anything to me. Here is the code.

   <body>
     
        <h2>The number guess game</h2>
        <form method="POST" action="">
            <label>Enter Number:</label>
            <input type="number" name="num">
            <input type="submit" name="submit" value="Send">
        </form>
        <div>
            <?php echo $message; ?>
        </div>
        
        <?php
            $message="";
            if(isset($_POST["submit"])) {
                $num = $_POST['num'];
                $random = rand(1, 100);
                if ($num == $random) {
                    $message= "You Win!";
                } else {
                    $message= "You Lose!";
                  }
             }
             else{
                echo "Enter The Number";
             }   
        ?>
     </body>

2

Answers


  1. The error message indicates that the PHP variable $message is being used before it is declared. This is because PHP code is executed sequentially, and if a variable is used before it is defined, it will result in an error.

    To resolve this issue, the entire code block within the second <?php tags should be moved before the tag. This will ensure that the $message variable is declared and initialized before it is used, preventing the undefined variable error.

    Login or Signup to reply.
  2. try this code

    <body>
        <?php
            $message="";
            if(isset($_POST["submit"])) {
                $num = $_POST['num'];
                $random = rand(1, 100);
                if ($num == $random) {
                    $message= "You Win!";
                } else {
                    $message= "You Lose!";
                  }
             }
             else{
                $message= "Enter The Number";
             }   
        ?>
        <h2>The number guess game</h2>
        <form method="POST" action="">
            <label>Enter Number:</label>
            <input type="number" name="num">
            <input type="submit" name="submit" value="Send">
        </form>
        <div>
            <?php echo $message; ?>
        </div>
        
        
     </body>
    

    You have called your $message variable before php code is executed. so the $message variable is always blank. code above will show message value based on post field or error message

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search