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
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.
try this code
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