Why is the num_tries counter not working? - php

Hi I am clearing my basics of php and i am kind of stuck in implementing this guess game. My problem is that I want $num_tries to work as a counter and it increases everytime by 1 whenever the user answers incorrectly.
<?php
$target=58;
$message="";
$num_tries=0;
if(isset($_POST["num_tries"])) {
print "set";
++$num_tries;
} else {
print "not set";
$num_tries=0;
}
if (!isset($_POST["guess"])) {
$message="Welcome to the game of Guess!!!!!!";
} elseif($_POST["guess"]> $target) {
$message= "Try a smaller Number";
} elseif($_POST["guess"] < $target) {
$message= "Try a larger Number";
} else {
$message= "congrats....You got it.";
}
?>
<HTML>
<HEAD><TITLE>Guess Game</TITLE>
</HEAD>
<BODY>
<H1><?php print $message ?></H1>
Guess Number:<?php print $num_tries ?>
<FORM action="<?php print $_SERVER['PHP_SELF'];?>" method="POST">
<INPUT type="text" name="guess">
<INPUT type="hidden" name="num_tries" value="<?php $num_tries?>">
</FORM>
</BODY>
</HTML>

You can solve it in your first lines:
$target=58;
$message="";
$num_tries = (!empty($_POST['num_tries']) ? $_POST['num_tries'] : 0);
That means if the form is not submitted before, $num_tries will be zero, otherwise, the value will be the last submitted value.
And then you need to print in the hidden element
<INPUT type="hidden" name="num_tries" value="<?php echo $num_tries?>">
---------------------------------------------------^^^^

$message="";
$num_tries=0;
change the above declaration to $num_tries=isset($_POST["num_tries"]) ? $_POST["num_tries"] : 0; which means if the post var value is set, then assign post var value, else assign 0.
and next change what you need to make is printing the value under hidden element.
you can use print or print_r or echo.
<INPUT type="hidden" name="num_tries" value="<?php echo $num_tries; ?>">

You are using <?php $num_tries ?> which literally does nothing.
You need to use <?php echo $num_tries ?> (print also works, but for your use case, echo is more efficient) in order to actually place the value into the form.
Additionally, $num_tries = 0; will not bother reading the existing value. You can use $num_tries = $_POST['num_tries'] | 0; although it will generate a PHP notice when the field isn't set, if you care about this, use isset with a ternary operator or if/else.

Related

Testing PHP POST empty values - unexpected result - What am I missing?

I am following a tutorial but I keep getting a TRUE result that shouldn't be correct if I click the submit button WITHOUT filling in any value in the name field.
The first test works as expected, but the second and third test keep returning TRUE when they should return FALSE (leaving the input empty).
What am I missing, not understanding, or doing wrong? This should be simple.
Any help or suggestions are appreciated.
Here is the very simple script:
<?php
//This one works correctly
if(!empty($_POST['name'])) {
echo "There is input here <br>";
} else {
echo "You have not input any info yet. <br>";
}
//This returns true even if I leave the field empty
if(isset($_POST['name'])) {
echo "A name has been input <br>";
} else {
echo "You have not input your name yet. <br>";
}
//This returns true also when it shouldn't
if(filter_has_var(INPUT_POST, 'name')) {
echo $_POST['name'] . ' <- Name Input!<br>';
} else {
echo 'No Name Input.';
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p><label for="name">Name:</label> <input type="text" name="name"
id="name" size="30" value=""></p>
<p><input type="submit" value="SEND"></p>
</form>
empty does what is says, checks if empty (is empty if not existing aswell)
isset checks if the var exists, no if anything has been set
filter_has_var pretty much the same as isset
place a print_r($_POST) at the top of your file, you will understand :)
You need to check the value to see if it's empty:
if(isset($_POST['name']) && !empty($_POST['name'])) {
http://php.net/manual/en/function.empty.php

Using isset or is not set with variable in PHP?

I have a form which submits data, and as a test I am attempting to first check if a variable is set on submit. If the variable is set, a text will be displayed stating something like "Variable is set". However if it isn't set, a text will be displayed saying "variable not set", once the variable hasn't been set it should then be set so next time when the form is submitted it displays variable is set however this is not working for me, for some reason it always displays that the variable is not set, my PHP code will be below:
<?php
if (isset($test)) {
echo "This var is set";
}
if (!isset($test)) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
I feel really stupid for not being able to do something which seems so easy, I am only just learning and sort of trying to teach myself, thank you for any help provided!!!
Working code and explanation:
<?php
$test="";
if (isset($_POST["text"])) { //always directly check $_POST,$_GET var without assigning
echo "This var is set";
$test=$_POST["text"]; // then assign
}
else{ // and use else clause for otherwise case
echo "This var is not set";
$test = 'set'; // AND if you want set to default/custom value in case of not set.
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off">
<br /><br />
<input type="submit" value="submit">
</form>
If you are using form to submit values, then try this one,
if (isset($_POST['text'])) {
echo "This var is set";
}
if (!isset($_POST['text'])) {
echo "This var is not set";
$test = 'set';
}
Otherwise, If a variable set to empty value like $test = '';
(It means variable is set but it has no values) It will execute your first if condition only.
<?php
$test=$_GET["text"];
if (isset($test)) {
echo "This var is set";
}
if (!isset($test)) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="#" method="get">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>
You haven't declared the variable $test.
Unless you've still got a bit of PHP somewhere that you haven't included here, your variable is empty. When a form is submitted, the input will be added to either the $_POST array (for method = "post") or else the $_GET array (for method = "get").
To Fix:
<?php
if (isset($_POST['text'])) {
$test = $_POST['text'];
echo "This var is set";
}
if (!isset($_POST['text'])) {
echo "This var is not set";
$test = 'set';
}
?>
<form action="" method="post">
<input type="text" id="text" name="text" autocomplete="off"><br><br>
<input type="submit" value="submit">
</form>

Session variable not working

I am using one session variable in my php page. As per my infomation, it is accessible throughout the program and it is, but problem is that it is showing different value for the same variable at different place in php page?
the code is as follows
<html><body>
<?php session_start();
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
?>
<form>
<input type="submit" name="save" value="save" />
</form>
<?php
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
?>
</body></html>
value becomes different before and after submit button click? Please tell me why it is so?
thanks in advavnce.
You are redeclaring the value of session variable 'x' here
$_SESSION['x'] = $_SESSION['x']+1;
This is why its appearing 1 greater than its initial value.
it is due to the code itself
if(isset($_SESSION['x'])) //It is set
$_SESSION['x'] = $_SESSION['x']+1; //Add 1 to the value
echo $_SESSION['x']."<br>"; return value with +1
Solution
The reason the output is different is the order you echo and update
//Echo
//Update Value
//Echo again
Simple solution would be to move this
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
to above this
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
Also note set the method and the action in the form to make sure it calls itself
<form method="GET" action="[url to itself]">
<input type="submit" name="save" value="save" />
</form>
Do it like this :
<html><body>
<?php session_start();
if(!isset($_SESSION['x']))
$_SESSION['x']=1;
echo "X=". $_SESSION['x'];
?>
<form method="GET" action="">
<input type="submit" name="save" value="save" />
</form>
<?php
if (isset($_GET['save']))
{
if(isset($_SESSION['x']))
echo $_SESSION['x']."<br>";
}
else
echo "no submit";
?>
</body></html>
this way the code prints out the same value after submit as it did before.
Either way you try if you print value and change after or change value and print after, when page reloads it will change value. you could add another button called increment and add the following code inside the php :
if (isset($_GET['inc']))
{
if(isset($_SESSION['x']))
$_SESSION['x'] = $_SESSION['x']+1;
}
and this one inside the form:
<input type="submit" name="inc" value="inc" />
this way youre variable increment when you press the inc button

Validate empty field with php

I need to validate an empty field with php and javascript, but both of the methods fail.
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<input type="text" name="pickupaddress" value="<?
if($pickupaddress == ''){
echo "";}
else{echo htmlentities($pickupaddress);}?> " id="pickupaddress"/>
<input type ="submit" name="submit" value"Reserve"/>
</form>
//////// Php validation DOES NOT WORK////////
$pickupaddress ='';
$err ='';
$pickupaddress = $_POST['pickupaddress'];
if($pickupaddress == ''){ //if empty field, I also tried == ""
$err.="Please provide pick up address.";
}
///// Javascript validation does not work.
if(form.pickupaddress ==""){
alert("empty address!");
}
//when I click submit nothing happens.
//I am thinking the problem is with
htmlentities($pickupaddress);
//Thanks for your help.
Here is hopefully simpler answer:
$pickupaddress = trim($_POST['pickupaddress']); //trims the string
if (empty($pickupaddress)){ //if empty field
$err.="Please provide pick up address.";
}
On the php side you can try trimming the value and then using empty() on the next line, though that will also invalidate 0, false, null, and other such values. Or you can try using isset.
For the javascript side you can try this function:
function IsEmpty(aTextField) {
if ((aTextField.value.length==0) ||
(aTextField.value==null)) {
return true;
}
else { return false; }
}
found here: http://www.codetoad.com/javascript/isempty.asp
$cid = $_POST['category'];
if (!empty($_POST['category']))
{
echo "<script>alert('empty field');</script>";
}
Where are you defining pickupaddress? Is it before the form or after? If the variable isn't defined, and depending on your server configuration, the value field of the input could be
Notice: undefined variable pickupaddress
Thus making the value != ''.
View your page source to ensure that the value is indeed empty.
there was a spave " " in your string: echo htmlentities($pickupaddress);}?> "
maybe that was the reason, because it was not an empty string but it was a space?
<form method="POST" name="contact_form"
action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>">
<input type="text" name="pickupaddress" value="<?
if($pickupaddress != '') {
echo htmlentities($pickupaddress);
}?>" id="pickupaddress"/>
<input type ="submit" name="submit" value"Reserve"/>
</form>
and i guess you might want to have checked if the post value is set:
if(isset($_POST['pickupaddress'])) {
$pickupaddress = $_POST['pickupaddress'];
}
the php way works for me like that ;) (the message is displayed if i dont write anything)

PHP How to check if text field matches var

Well then, this is likely to be the n-th time someone is asking this, but honestly I didn't grab anything useful spending the last hour or so on Google. What I want to do is rather trivia, or so I thought. I have this working in Java Script but want to move it to PHP. In brief:
declare a var with a static value
add text field into which user is asked to enter value of above var
check if field is a) empty, b) non-empty mismatch, or c) non-empty match
My (limited) PHP wisdom has lead me into believing it ought to be something like the below, but apparently it's not. I'd very much appreciate any insight, tha.
<?php
$coconew = "blah";
if (isset ($_POST["cocosub"])) {
if ($_POST["cocoval"] == "") {
echo "empty";
} else {
if ($_POST["cocoval"] != $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form action="<?php $_SERVER['PHP_SELF'] ?>" id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval">
<input type="submit">
</div>
</form>
You need to change
<input type="text" id="cocoval">
to
<input type="text" name="cocoval">
There are other (and probably better) ways to do this, but you are on the right track.
$_POST only looks for the name attribute of form elements, so modify your form as such:
<?php
$coconew = "blah";
if (isset ($_POST["cocoval"])) {
if ($_POST["cocoval"] === "") {
echo "empty";
} else {
if ($_POST["cocoval"] !== $coconew) {
echo "mismatch";
} else {
echo "match";
}
}
}
?>
<form id="cocosub" method="post">
<div>
<?php echo $coconew; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit">
</div>
</form>
(I made a few other changes, you want to check isset on the element, not the form, it will POST to the same page if you don't give it an attribute [so no need to add the echo], and adding better type checking in your php)
in addition to the other answers already posted, you might also be interested in PHP's session support (depending on how "static" you need your static variables to be). That's where you'd put $cocoval and any other variables if you need to save their values across multiple requests for the same URL by the same user. See here for more info:
http://php.net/manual/en/features.sessions.php and
http://www.php.net/manual/en/book.session.php
This works:
<?php
session_start();
if(isset($_POST["cocosub"])){
$input = trim($_POST["cocoval"]);
if($input == ""){
echo "empty";
} elseif($input != $_SESSION["coconew"]){
echo "mismatch";
} else {
echo "match";
}
}
$_SESSION["coconew"] = substr(md5(uniqid()), 0, 5);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="cocosub" method="post">
<div>
<?php echo $_SESSION["coconew"]; ?>
<input type="text" id="cocoval" name="cocoval">
<input type="submit" name="cocosub">
</div>
</form>
You needed to add name="cocosub" to the Submit button element in order for the first if(isset(...)) condition to be true. That's why the script didn't work. Also, instead of id, you need to use the name="cocoval" in the input text field as well in order for it to carry over into $_POST.

Categories