A simple number guessing program in php using HTML Form - php

<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Welcome to my guessing game</h1>
<form action="" method="GET">
<label for="numinput">Enter your number</label>
<input type="text" name="numinput">
<input type="submit" name="submit">
</form>
<?php
$num = $_GET['numinput'];
if (!isset($_GET['num'])) {
echo("Missing Guess Parameter");
} elseif ( strlen($_GET['num']) <60){
echo ("Your guess is too short");
} elseif ( !is_numeric($_GET['num'])){
echo("Your guess is not a number");
} elseif ($_GET['num'] > 60){
echo ("Your guess is too high");
} else {
echo ("Congratulations - You are right");
}
?>
</html>
My goal is to create a simple number guessing game using $_GET in php
Output: "Missing Guess Parameter" despite i provide any number in the input. Also, I couldn't understand whether to get the user provided data from submit of the textbox.

You need to put $num instead of $_GET['num'] after the variable $num is set
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Welcome to my guessing game</h1>
<form action="" method="GET">
<label for="numinput">Enter your number</label>
<input type="text" name="numinput">
<input type="submit" name="submit">
</form>
<?php
$num = $_GET['numinput'];
if (!isset($num)) {
echo("Missing Guess Parameter");}
elseif ( strlen($num) <60){
echo ("Your guess is too short");}
elseif( !is_numeric($num)){
echo("Your guess is not a number");}
elseif ($num > 60){
echo ("Your guess is too high");}
else{
echo ("Congratulations - You are right");}
?>
</html>

Name of the html input and the key of $_GET must be identical, so change name="numinput" to name="num" will be a solution to fixed the problem.
NB: $num = $_GET['num']; may accure UNDEFINED INDEX if you use it outside the if condition when isset($_GET['num']) equal to true
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1>Welcome to my guessing game</h1>
<form action="" method="GET">
<label for="numinput">Enter your number</label>
<input type="text" name="num">
<input type="submit" name="submit">
</form>
<?php
//$num = $_GET['num']; this should be after isset($_GET['num']) == true
if (!isset($_GET['num'])) {
echo("Missing Guess Parameter");
} elseif ( strlen($_GET['num']) <60){
echo ("Your guess is too short");
} elseif ( !is_numeric($_GET['num'])){
echo("Your guess is not a number");
} elseif ($_GET['num'] > 60){
echo ("Your guess is too high");
} else {
echo ("Congratulations - You are right");
}
?>
</body>
</html>

Related

How to create a form that accept number only

How can I create a form that accept number only?
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
<label>x:</label><br>
<input type="text" name="xx" ><br>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['xx']) || !empty($_POST['xx']) || is_numeric($_POST['xx'])){
$x = $_POST['xx'];
}else{
echo "vous devez taper des chiffres!";
}
echo $x . "<br />";
?>
</body>
</html>
I am new in PHP please an easy answer.
Thank you :-)
If you only want to accept a number, you can also do so using the html element <input>.
Like this:
<input type= "number" name= "xx">
As a precaution, check the server-side $ _POST["xx"] element. Whether the element contains the expected values.
Like this:
check whether the element has been filled in and does not contain only white characters.
And remove any white space before and after the number using trim()
$xx = trim($_POST["xx"]);
if(!empty($xx) && is_numeric($xx)) {
// if "if-condition" true
} else {
// if "if-condition" false
}
I have this message if it is empty
enter image description here
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES, "utf-8"); ?>">
<label>x:</label><br>
<input type="number" name="xx" ><br>
<input type="submit" value="Submit">
</form>
<?php
$value = trim($_POST["xx"]);
if(!empty($value) && is_numeric($value)) {
$xxx = $_POST['xx'];
} else {
echo "vous devez taper des chiffres!";
}
echo $xxx . "<br />";
?>
</body>
</html>
It is not an answer this, I don't know how to add code in the comment.

PHP code is showing in the webpage while executing

i am new to php I am trying to write a registration page.But something goes wrong.Every time i try to execute the code i get something like this in my page
Database details
Db name: cibil,
table name: table {id,username,password,email
}
query($sql)===true) { $_SESSION['message']='You are successfully added';
$_SESSION['username']=$user; $_SESSION['email']=$email;
header(location:page.php); } else{ $_SESSION['message']='Something went wrong'; } } ?>
My code is
<? php
session_start()
$_SESSION['message']='';
if($_SERVER['REQUEST_METHOD']=='POST')
{
$conn=new mysqli('localhost','root','','cibil') or die("error");
$user=$_POST['user'];
$pass=$_POST['pass'];
$email=$_POST['email'];
$sql="INSERT INFO table (username, password,email)VALUES('$user','$pass','$email')";
if($conn->query($sql)===true)
{
$_SESSION['message']='You are successfully added';
$_SESSION['username']=$user;
$_SESSION['email']=$email;
header(location:page.php);
}
else{
$_SESSION['message']='Something went wrong';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register form</title>
<link rel="stylesheet" type="text/css" href="reg_style.css">
</head>
<body>
<div id="h1">
<h1>Registration Page</h1>
</div>
<div id="err"><? php echo $_SESSION['message'] ?></div>
<div id='form'>
<form method="post" name='form' onsubmit="return rvalidate()" action="">
<p class="error">*Required</p>
<label for="user">Enter Your Name* : </label>
<input id="user" type="text" name="user" class="field">
<span class='error'></span><br><br>
<label for="email">Enter Your Email : </label>
<input id="email" type="text" name="email" class="field">
<br><br>
<label for="pass">Enter Your Password* : </label>
<input type="password" id="pass" name="pass" class="field"><span class='error'></span><br><br>
<label for="rpass">Re-Enter Your Password* : </label>
<input type="password" id="rpass" name="rpass" class="field"><span class='error'></span><br><br>
<input type="submit" id='submit' class="field" value="SUBMIT" onclick="validate();" >
</form>
</div>
<br><br>
<div id="login_text">
<b>If you are already register </b><br>Click here
</div>
<script type="text/javascript">
var error=document.getElementsByTagName('span');
var user=document.form.user;
var pass=document.form.pass;
var rpass=document.form.rpass;
function validate()
{
if(user.value==="")
{
error[0].innerHTML="*Enter Your name";
user.setAttribute("style","border-color:green");
}else{
error[0].innerHTML="";
user.setAttribute("style","border-color:initial");
}
if(pass.value=="")
{
error[1].innerHTML="*Password is Required";
pass.setAttribute("style","border-color:green");
}else{
error[1].innerHTML="";
pass.setAttribute("style","border-color:initial");
}
if(pass.value!==rpass.value)
{
error[2].innerHTML="*Password Missmatch";
rpass.setAttribute("style","border-color:green");
}else{
error[2].innerHTML="";
rpass.setAttribute("style","border-color:initial");
}
}
function rvalidate()
{
if (error[0].innerHTML=="" && error[1].innerHTML=="" && error[2].innerHTML=="") {
return true;
}
else{
return false;
}
}
</script>
</body>
</html>
Thank you for your help.........
Your code is not executed and shown as text because you have a space between ? and php at the start of the code. Try to start with <?php
session_start();. Then you will be able to debug all the rest :)
<div id="err"><? php echo $_SESSION['message']
If you notice there is a space between the ? And PHP, that may affect what is bring output. There is a few areas where your quotes don't match so if you check if the quotes aren't closing each other in places they shouldn't be closed then you should be okay
Is your filename correct? If it is a .htm or .html file it may not parse the PHP which could also be another issue you're having
You have a space at the opening of your php code :
<? php
should be :
<?php
Your code:
$sql="INSERT INFO table (username, password,email)VALUES('$user','$pass','$email')";
Must be without `...`:
$sql="INSERT INFO table (username, password,email)VALUES($user, $pass, $email)";

PHP help me with this some notifications

I'm having a hard time figuring how to fix this notification. I already did it but the result was the code didn't work. My logic is not that high here is the code:
Here is the error.
Would you also explain why the gender is undeinfed but the textbox and textarea was just fine?
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$x=$_POST['name'];
$y=$_POST['email'];
$z=$_POST['website'];
$c=$_POST['comment'];
$v=$_POST['gender'];
if($x == '' or $y == '' or $z==''or $c=='' or $v==''){
echo "* required all fields";
}else{
$result=$x.'<br>'.$y.'<br>'.$z.'<br>'.$c.'<br>'.$v;
}
}
?>
<form action="" method="post">
NAME:<input type="text" name="name"><br><br>
EMAIL:<input type="text" name="email"><br><br>
WEBSITE:<input type="text" name="website"><br><br>
<textarea name="comment" rows="5" cols="40"></textarea><br><br>
GENDER:<input type="radio" name="gender" value="Male">MALE
<input type="radio" name="gender" value="Female">Female<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h3>YOUR INPUT:</h3>";
echo $result;
?>
</body>
</html>
if($x == '' ||$y == '' || $z=='' || $c=='' || $v==''){
echo "* required all fields";
}else{
You cant user or man check the PHP manual
try this way
if(($x="" || empty($x))&&($y="" || empty($y))&&($z="" || empty($z)))
{
echo "* required all fields";
}
may be it will help
What you need is a JS function to validate your radio buttons at first, or you could also use the HTML attribute required (I have written both of them) followed by only a few if-statements This should work just fine.
<!DOCTYPE HTML>
<html>
<head>
<script>
function validateForm(){
for(i=0; i<document.form.radios.length; i++){
if(document.form.radios[i].checked==false){
c=1;
}
else{
c=0;
break;
}}
if(c==1){
alert('Please select an option');
}
}
</script>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$x=$_POST['name'];
$y=$_POST['email'];
$z=$_POST['website'];
$c=$_POST['comment'];
if($x == '' or $y == '' or $z==''or $c=='')
{ echo "* required all fields";
}else{
$result=$x.'<br>'.$y.'<br>'.$z.'<br>'.$c;
}
}
?>
<form action="" method="post">
NAME:<input type="text" name="name"><br><br>
EMAIL:<input type="text" name="email"><br><br>
WEBSITE:<input type="text" name="website"><br><br>
<textarea name="comment" rows="5" cols="40"></textarea><br><br>
<input type="radio" name="gender" value="Male" required /> Male
<input type="radio" name="gender" value="Female" /> Female
<input type="submit" name = "submit" value="SAVE" />
</form>
<?php
if(isset($_POST['submit']))
{
if(!($x == '' or $y == '' or $z==''or $c=='')){
echo "<h3>YOUR INPUT:</h3>";
echo $result;
}else
echo "NOT ALL FIELDS WERE SELECTED.";}
?>
</body>
</html>
You have some undefined variables.In order to make it work try this:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$result = '';
$x = '';
$y = '';
$z = '';
$c = '';
$v = '';
if(isset($_POST['submit'])){
if(isset($_POST['name'])){
$x= $_POST['name'];
}
if(isset($_POST['email'])){
$y=$_POST['email'];
}
if(isset($_POST['website'])){
$z=$_POST['website'];
}
if(isset($_POST['comment'])){
$c=$_POST['comment'];
}
if(isset($_POST['gender'])){
$v=$_POST['gender'];
}
.......
But you should separate your HTML code from the PHP,
maybe creating and index.html and from.php file.
Keeping all into the same file is a very bad practice.
$v=isset($_POST['gender'])?$_POST['gender']:'';

(PHP) Adding a 'guess counter' to a random number game

I need to modify a block of code and add a counter regarding how many times it took the user to guess the right number.
I was wondering how it would be properly implemented into my code.
This is what I have so far.
<?php
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$count++; //Declare the variable $count to increment by 1.
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
You have to use PHP Sessions to keep track of the count.
All you have to do is initialize counter to 0 and have it increment when the user guesses a number
<?php
session_start();
if (!isset($_POST["guess"])) {
$_SESSION["count"] = 0; //Initialize count
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
echo $_POST["numtobeguessed"];
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
$_SESSION["count"]++; //Declare the variable $count to increment by 1.
} else { // must be equivalent
$_SESSION["count"]++;
$message = "Well done! You guessed the right number in ".$_SESSION["count"]." attempt(s)!";
unset($_SESSION["count"]);
//Include the $count variable to the $message to show the user how many tries to took him.
}
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
This should work for you.
$count = isset($_POST['count']) ? $_POST['count'] : 0; //Use post value if defined. If not set to 1.
if (!isset($_POST["guess"])) {
$message = "Welcome to the guessing machine!";
$_POST["numtobeguessed"] = rand(0,1000);
} else if ($_POST["guess"] > $_POST["numtobeguessed"]) { //greater than
$message = $_POST["guess"]." is too big! Try a smaller number.";
} else if ($_POST["guess"] < $_POST["numtobeguessed"]) { //less than
$message = $_POST["guess"]." is too small! Try a larger number.";
} else { // must be equivalent
$message = "Well done! You guessed the right number in ".$count." attempt(s)!";
//Include the $count variable to the $message to show the user how many tries to took him.
}
$count++;
?>
<html>
<head>
<title>A PHP number guessing script</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<form action="" method="POST">
<p><strong>Type your guess here:</strong>
<input type="text" name="guess"></p>
<input type="hidden" name="numtobeguessed"
value="<?php echo $_POST["numtobeguessed"]; ?>" ></p>
<input type="hidden" name="count"
value="<?php echo $count; ?>" ></p>
<p><input type="submit" value="Submit your guess"/></p>
</form>
</body>
</html>
on 22.6.2021 i wrote a Guess Number in Range [0 .. aMaxIntValue] sample Web Application using PHP. i think the following code may help you. the code is kept in a Single PHP file. it generates #4 HTML pages ...
the 1st initial page is used to collect application parameters (e.g. the Max Int Number to Guess)
the 2nd page is the Main Play Game Page where the user is asked to Guess the Secret Number or to Reset Game. this page shows the previous user guesses and some tips for the user about the guess
the 3rd page is used to notify the user looses game (that is he has no more tries left)
the 4th page is used to notify the user wins the game (that is the Guess was OK)
the Number of Tries left to the User is computed using the values range [0 .. max]
the Secret Number to Guess is a random generated integer number
this is the PHP + HTML code ...
<?php
session_start();
error_reporting (E_PARSE | E_COMPILE_ERROR);
function ResetGame()
{
unset ( $_SESSION['theMaxNumber'] );
}
function InitGame()
{
$_SESSION['theNumberToGuess'] = mt_rand (0, $_SESSION['theMaxNumber']);
$_SESSION['theMaxNumberOfTries'] = floor ( log ($_SESSION['theMaxNumber'], 2) ) + 1;
$_SESSION['theUserTriesCount'] = 0;
$_SESSION['thePrevGuessesString'] = '';
$_SESSION['theUserGuess'] = 0;
}
function ComputeNumberOfTriesLeft()
{
return $_SESSION['theMaxNumberOfTries'] - $_SESSION['theUserTriesCount'];
}
function IsNoMoreTriesLeft()
{
return ComputeNumberOfTriesLeft() <= 0;
}
$aCanPlayGame = false;
$aUserSubmittedGuess = false;
$aIsNoMoreTriesLeft = false;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ( isset ($_REQUEST['playgame']) ) {
$_SESSION['theMaxNumber'] = intval($_REQUEST['theMaxNumber']);
// init game ...
InitGame();
$aCanPlayGame = true;
}
elseif ( isset ($_REQUEST['submituserguess']) ) {
$aCanPlayGame = true;
$aUserSubmittedGuess = true;
$_SESSION['theUserGuess'] = intval($_REQUEST['theUserGuess']);
}
elseif ( isset ($_REQUEST['resetgame']) ) {
ResetGame();
}
else {
ResetGame();
}
}
else {
ResetGame();
}
// check a play
$aUserShouldTryLower = false;
$aUserShouldTryHigher = false;
$aUserWins = false;
$aUserLooses = false;
if ($aCanPlayGame) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ( ! $aIsNoMoreTriesLeft ) {
// user have tries left
if ($aUserSubmittedGuess) {
// check user guess ...
$aUserGuess = intval($_SESSION['theUserGuess']);
if ( $aUserGuess > $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryLower = true;
}
elseif ( $aUserGuess < $_SESSION['theNumberToGuess'] ) {
$aUserShouldTryHigher = true;
}
else {
$aUserWins = true;
// also reset game
ResetGame();
}
// add the current guess to the prev guesses string
$_SESSION['thePrevGuessesString'] .= $_SESSION['theUserGuess'] . ' ';
// increase the user tries count
++ $_SESSION['theUserTriesCount'];
// check tries count
if ( ! $aUserWins ) {
$aIsNoMoreTriesLeft = IsNoMoreTriesLeft();
if ($aIsNoMoreTriesLeft) {
// this was the last try
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
}
}
else {
// no more tries left
$aUserLooses = true;
// also reset game
ResetGame();
}
}
?>
<?php if ($aUserLooses): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Sorry, you loose the game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aUserWins): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Congrats, you Win the Game</p>
<p>the Number to Guess was <?php echo $_SESSION['theNumberToGuess']; ?></p>
<form method="post">
<input type="submit" name="resetgame" value="reset game">
</form>
</body>
</html>
<?php elseif ($aCanPlayGame): ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>the Max Number is <?php echo $_SESSION['theMaxNumber']; ?></p>
<p>Guess a Number in the Range [ 0 .. <?php echo ($_SESSION['theMaxNumber']); ?> ]</p>
<p>[DEBUG] the secret number to guess is <?php echo $_SESSION['theNumberToGuess']; ?></p>
<p>you have <?php echo ComputeNumberOfTriesLeft(); ?> tries left</p>
<form method="post">
<label for="theUserGuess">Enter your Guess: </label>
<input type="text" id="theUserGuess" name="theUserGuess">
<input type="submit" name="submituserguess" value="Guess">
<input type="submit" name="resetgame" value="reset game">
</form>
<p>Prev Guesses: <?php echo $_SESSION['thePrevGuessesString']; ?> </p>
<p>
<?php
if ($aUserShouldTryLower) {
echo 'you should try a lower < guess';
}
elseif ($aUserShouldTryHigher) {
echo 'you should try a higher > guess';
}
else {
echo 'no guess';
}
?>
</p>
</body>
</html>
<?php else: ?>
<!DOCTYPE html>
<html>
<head>
<title>Guess a Number</title>
</head>
<body>
<p>Guess a Number from (0) to ... </p>
<form method="post">
<input id="theMaxNumber" name="theMaxNumber">
<input type="submit" name="playgame" value="play game">
</form>
</body>
</html>
<?php endif; ?>
that's all folks ...

number of tries does not increment in the PHP number-guessing game

The PHP script below is for a number-guessing game. A hidden field is used to store the number of guesses, represented by the variable $tries. No matter how I tried, the number of guess ($tries) never increment. Could someone tell me what is wrong with the code please?
Maria
<?php
$num=21;
$tries=(isset($_POST['guess'])) ? $tries+1: 0;
if (!isset($_POST['guess'])) {
$message="Welcome to the Guessing Game!";
} elseif (!is_numeric($_POST['guess'])) {
$message="You need to type in a number.";
} elseif ($_POST['guess']==$num) {
$message="You WON 1 million point!";
} elseif ($_POST['guess']>$num) {
$message="Try a smaller number";
} else {
$message="Try a bigger number";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Guessing Game</title>
</head>
<body>
<h1><?php echo $message; ?></h1>
<p><strong>Guess number: </strong><?php echo $tries; ?></p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p><label for="guess">Type your guess here:</label><br/>
<input type="text" id="guess" name="guess" />
<input type="hidden" name="tries" value="<?php echo $tries; ?>"/></p>
<button type="submit" name="submit" value="submit">Submit</button>
</form>
</body>
</html>
Change:
$tries=(isset($_POST['guess'])) ? $tries+1: 0;
To:
$tries=(isset($_POST['tries'])) ? $_POST['tries']+1: 0;
Or, depending on the condition, only increment when a guess exists, then:
$tries=(isset($_POST['guess'])) ? $_POST['tries']+1: 0;
But doing it based on guess will allow the person to reset the counter by not entering a number ;)
$tries is not defined when you are trying to increment it. However it is availabe in $_POST
$tries=(isset($_POST['guess'])) ? $tries+1: 0;
// Change to
$tries=(isset($_POST['guess'])) ? $_POST['tries']+1: 0;

Categories