$i=0;
while (db_data) {
$i++;
echo '<input type="checkbox" name="v['.$i.']" value="'.$url.'"';
if ($v[$i]) {
echo ' checked';
$s .= $url;
}
echo '/>';
}
I have the above array of checkboxes. It worked on my pc, but not on the server; it seems like the confusing part is on $v[$i].
$v is not defined, but sure used no where else. the problem is my checkbox selection never restored, and code never get into the if statement.
however, if i add the following, i can see the value. just the checkbox lost after the processing
$v=$_POST['v'];
while (list ($key,$val) = #each ($v)) {
$x .= ' 11*'.$key.'-'.$val.'*22 ';
}
my goal is to preserve the checkbox checked on the form, and i need the $s elsewhere. any solution to replace $v[$i]?
Can anybody help me fix this? Thank you.
The issue seems to be $v = $_POST. If you are just doing that then your conditional statement would need to be
if ($v['v'][$i]) {
///Checkbox
}
or just do $v = $_POST['v'].
Sorry, ignore above as you did mention you did that part. See below.
Here is working code.
<form action="" method="post">
<?php
$v = $_POST['v'];
$i=0;
while ($i < 4) {
$i++;
$url = "test.com/".$i;
echo '<input type="checkbox" name="v['.$i.']" value="'.$url.'"';
if ($v[$i]) {
echo ' checked="checked"';
$s .= $url;
}
echo '/> '.$url.'<br />';
}
?>
<input type="submit" name="submit" value="submit" />
</form>
I left the code pretty much the same to show you where you went wrong, but you should be checking the $_POST variable for exploits before using. If I were doing this as well, I would use a for count, but it's setup as a placeholder for your database code. Make sure that $url gets populated as well.
You could also do away with the $i variable like:
<?php
$v = $_POST['v'];
while (db_data) {
echo '<input type="checkbox" name="v[]" value="'.$url.'"';
if (is_array($v)) {
if (in_array($url,$v)) {
echo ' checked="checked"';
$s .= $url;
}
}
echo '/> '.$url.'<br />';
}
?>
Try to print_r($_POST) and then print_r($v) and see if anything comes up. If the $_POST works, then you know that it is being posted back to the page correctly. Then if the $v is working, then you know you set $v = $_POST correctly. Due to the fact that you don't actually give us any information on the db_data, I assume this is working correctly and displaying all the checkboxes on first load, so as long as it is posted and you are setting the $v variable, it should be working.
A side note is that you should validate the $_POST variables before using, but do that after you get things working.
change
name="v['.$i.']"
to
name="v[]"
the fact that PHP picks that up as an array is a unintended feature of PHP that wasn't intentionally designed. you don't need to set the indexes, just define it as an array.
Related
Please can someone help me, I am trying to use the array function to give an overall variable a positive or negative value, based on the results of checkboxes.
The checkbox question is, which of the following reindeer exist, so for every reindeer that is correct I am looking to give the variable $finalvalue an increment value. Then leaving an IF function at the end to say if the wrong reindeer is ticked, give a decrement value, but as well as the increment values for the right ones.
I have attached the code below, every time I use it, the value does not increase as desired or is not cumulative for every correct reindeer.
Thanks.
HTML FIRST
Which of the following are of Santa's Reindeer?(You can select more than one answer)<br>
<input type="checkbox" name="reindeer" value="Rudolph">Rudolph<br>
<input type="checkbox" name="reindeer" value="Prancer">Prancer<br>
<input type="checkbox" name="reindeer" value="Dancer">Dancer<br>
<input type="checkbox" name="reindeer" value="Ronald">Ronald<br>
<br><br>
<input type="submit" value="Submit">
PHP SCRIPT RECIEVER SIDE
$reindeer=$_GET['reindeer'];
$type=array("Rudolph","Dancer","Prancer");
foreach($type as $reindeer){$finalvalue = $finalvalue+2;};
if ($reindeer=="Donald"){$finalvalue = $finalvalue-6;}
print "$finalvalue";
Thanks for any help.
<?php
$input = $_GET['reindeer'];
$valid = ["Rudolph","Dancer","Prancer"];
# Debug input..
echo 'Raw input data:<pre>';
var_dump($input);
echo '</pre>';
if(is_array($input)){
foreach($input as $reindeer){
if(in_array($reindeer, $valid)){
echo 'user supplied multiple answers and '.$reindeer.' is listed in $valid. </br>';
$finalvalue = $finalvalue+2;
} else {
echo 'user supplied multiple answers and '.$reindeer.' is listed <strong>not</strong> in $valid. </br>';
$finalvalue = $finalvalue-6;
}
}
} else {
# This code should never execute unless the user changes the html code.
if(in_array($input, $valid)){
echo 'user supplied 1 answer and '.$reindeer.' is listed in $valid. </br>';
$finalvalue = 2;
} else {
echo 'user supplied 1 answer and '.$reindeer.' is listed <strong>not</strong> in $valid. </br>';
$finalvalue = 0;
}
}
echo $finalvalue;
?>
Which of the following are of Santa's Reindeer?(You can select more than one answer)<br>
<input type="checkbox" name="reindeer[]" value="Rudolph">Rudolph<br>
<input type="checkbox" name="reindeer[]" value="Prancer">Prancer<br>
<input type="checkbox" name="reindeer[]" value="Dancer">Dancer<br>
<input type="checkbox" name="reindeer[]" value="Ronald">Ronald<br>
<br><br>
<input type="submit" value="Submit">
$input = $_GET['reindeer'];
$valid = ["Rudolph","Dancer","Prancer"];
foreach($input as $reindeer){
if(in_array($reindeer, $valid)){
$finalvalue = $finalvalue+2;
} else {
$finalvalue = $finalvalue-6;
}
}
Notice the brackets in the html. Adding those brackets to the name of the input makes it come as an array. Thus, produces much cleaner and minimal code.
Status:
Apprentice.
My PHP knowledge:
Beginner level.
What I am trying to achieve with my PHP code:
Update the health bar input when ever the user clicks on the submit button.
<form>
<input type="submit" value="Attack">
</form>
So if the condition is true and the post has been done then I want to subtract 25 from the variable health which is then equal to another variable named input.
The problem:
I cant figure out why the health is not updating and how to save the updated value even if the user refreshes and then substracting 25 with the updated health everytime the user clicks on "attack".
What I tried:
Apart from doing some PHP research about Session_start() im not sure how to use it in this context. Im not even entirely sure why my conditional is faulty. I get no error messages what so ever but when I remove my if statement and echo the my bar variable then it doesnt work either as I dont get any number at all, which of course makes me suspect that my math is not working.
<?php
$health = 100;
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
if (isset($_POST['submit'])) {
$health - 25 == $input;
echo $bar;
}
?>
Question:
Why does'nt my value of health / input update? How can I save the session and substract from the new variable the next time an attack is made?
Your PHP is stateless so it has no record of what health was - it's simply reset to 100 every time.
You need to either use sessions, or simply pass back in the value of health each time:
<?php
$health = (isset($_REQUEST['health']) ? (int) $_REQUEST['health'] : 100);
if (isset($_REQUEST['submit'])) {
$health = $health - 25;
}
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
?>
<form action="attack.php" method="post">
<input type="submit" name="submit" value="Attack">
<input type="hidden" name="health" value="<?php echo $health; ?>">
</form>
A couple of other points:
1) I'm not sure what the significance of $input is
2) You should really include a method in your form tag of either get or post - in the PHP I've used I have referenced $_REQUEST which features the values of both $_GET and $_POST
3) Notice I cast the value of $_REQUEST['health'] to an integer because this is output in the hidden HTML field and this helps to avoid XSS exploits.
If you want the health variable to carry over on to other pages or scripts then you might prefer to use a session. Revised code as follows:
<?php
session_start();
$health = (isset($_SESSION['health']) ? $_SESSION['health'] : 100);
if (isset($_REQUEST['submit'])) {
$health = $health - 25;
$_SESSION['health'] = $health;
}
$input = "";
$bar = '<div>' . $health . $input . '%' . '</div>' . '<div>' . 'Stamina' . '</div>';
echo $bar;
?>
<form action="attack.php" method="post">
<input type="submit" name="submit" value="Attack">
</form>
One final comment is that using the session method a user cannot tamper with their own health score. Whereas using the hidden input method the user could potentially change the value of the field and tamper with their health score if they had the technical know-how.
change the form to the form below -
<form action='' method='POST'>
<input type="submit" name='submit1' value="Attack">
</form>
Then you can do -
if (isset($_POST['submit1']))
{
echo "button was pressed";
/// do other stuff.....
}
Define your form like:
<form method="POST">
That might do the trick. And you might need an hidden input field for the current health.
Firstly, forms default to a GET method if omitted.
Therefore, you need to specify it in your form tag
method="post"
Then your conditional statement will fail, since the submit input doesn't have the name attribute.
Add name="submit" to it.
Then this $health - 25 == $input; that doesn't make any sense and I don't know what you're trying to do here.
As stated in another answer by Mr Carrot, you'd want to use $health = $health - 25;
I'll let you look through the answers given, but this gives you a good indication as to what's going on.
Using error reporting would have signaled notices.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
So I'm iterating through a set value via a for loop, which will echo html input fields, every other echo'd html input field behaves as expected (including the name and id fields of the one below), however I keep getting syntax errors when trying to set the value as a postback to retain them on page submit.
Here is my code:
$type = "number".$i;
echo '<input type="text" name="'.$type.'" id="'.$type.'" value="'.<?php if (isset($_POST[$type])) { echo $_POST[$type]; } else { echo NULL;}.'" />';
Thanks in advance.
You have an extra <?php statement in the row. Since the line is echo '...'. you don't need to declare that more php code is coming. You can do something like this instead:
echo '<input type="text" name="'.$type.'" id="'.$type.'" value="';
if (isset($_POST[$type])) echo $_POST[$type];
echo '" />';
Although personally, I prefer to do something like <input [...] id="{$type}" [...]" outside of the php code, less messy.
Hi I am a newbie learning PHP ( & on stackoverflow too)- I am trying to solve a simple problem but unable to do. I hae already searched on google and stackoverflow before posting a question as I didnt want to waste other time but for a week now am unable to solve this issue.
I am writing a simple program in php that lets user input a number and checks if the value entered is 5. If true it echo's "you win" else "try again". I am able to do this
The tricky part for me is I want to give him only 10 chances and try as I might using basic PHP am unable to do this. Have tried using if, for, do while but am unable to "loop the html"..I dont know jquery etc and am trying to accomplish this with PHP only. I havent yet progessed to learning sessions etc. Thanks in advance
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="hidden" name="cnt" value=<?php $cnt=0 ?>>
<input type="submit" name="go">
</body>
</html>
<?php
$i=0;
if ($_POST['num']!=5)
{
$i++;
echo $i;
echo " Please try again";
}
else
echo "You win the game";
?>'
You need to store the variable in some manner such that it persists. in your script, you are setting $i to 0 each time it runs. Plus you are setting the value incorrectly in your hidden input.
One way of doing this is using a Session variable, such as $_SESSION['cnt']
My PHP is a bit rusty, but here's an example using Session variables:
$max_guesses = 10;
if( !isset($_SESSION['cnt']) ){
$_SESSION['cnt'] = 0;
}
if( $_SESSION['cnt']++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
If you don't want to, or can't use a session variable, you could use the hidden input field, like you tried to:
<?php
if( !isset($_POST['cnt']) ){
$cnt = 0;
} else {
$cnt = $_POST['cnt'];
}
if( $cnt++ > $_max_guesses ){
echo "Maximum tries exceeded";
} else {
echo "Try again";
}
?>
<input type='hidden' name='cnt' value='<?php echo $cnt ?>' />
(Note if your form uses GET instead, just replace $_POST with $_GET or you can use $_REQUEST if you're not sure, but probably better not to.
After successful login of the user set the chances variable to 10 like this.
$_SESSION['nofchances']=10;
After setting this flag on the successful authentication page. Redirect to your PLAIN html code.
EDITED :
question.html
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<form method="POST" action="gullible.php">
Please enter any number :<input type="text" name="num">
<input type="submit" name="go">
</body>
</html>
gullible.php
<?php
if($_SESSION['nofchances']!=0)
{
if ($_POST['num']!=5)
{
$_SESSION['nofchances'] = $_SESSION['nofchances'] - 1;
echo "You have ".$_SESSION['nofchances']." no of chances to try";
echo "<br>Please try again";
header("location:question.html");
}
else
{
echo "You won the game";
$_SESSION['nofchances']=10; // resetting back
}
}
else
{
echo "Your chances expired";
}
?>
You can call a function in onBlur/onChange
<script>
function test()
{
var count=<?php echo $count;?>;
var guess=parseInt($('#hid_num').val())+1;
if(guess>count)
{
alert('Your chances over!');
}
else
{
$('#hid_num').val(guess);
}
}
</script>
<input type="text" onblur="test();" id="chk_estimate" />
<input type="hidden" value="0" id="hid_num" /></body>
If you dont want to use sessions yet you could define a hidden input field which stores the current try then incriment "+1" it whenever the submit is pressed / the site is reloaded. Something like:
if( isset($_POST['try']) ) {
$try = $_POST['try'];
$try += 1;
} else {
$try = 0;
}
add the hidden field in your form like:
$hiddenTry = '<input type="hidden" value="'. $try .'" name="try"/>';
and add a if clause to when to show the form like:
if ( $try <= 10 ) {
//your form
}
i made this for you i hope it can help you learn something new (i edited it a couple of times to make variable names easier to understand make sure you check it again - i added a cheat also :) )
<?php
session_start(); // with this we can use the array $_SESSION to store values across page views of a user.
mt_srand(time()); // this is to ensure mt_rand function will produce random values. just ignore it for now. it's another story :)
$max_tries = 10; // limit of guesses
$_SESSION['the_magic_number']=!isset($_SESSION['the_magic_number'])?mt_rand(0,100):$_SESSION['the_magic_number'];
// the previous line is a one-liner if then else statement. one-liners works like this:
// $my_name_will_be=($isBoy==true)?"George":"Mary";
if(isset($_POST['num'])) // if this pageview is from a valid POST then...
{
$_SESSION['current_try']=isset($_SESSION['current_try'])?$_SESSION['current_try']+1:1;
// one-line if then else again. This increases the try user is now, or resets it to one
}
?>
<html>
<body>
TRY AND GUESS THE NUMBER
<br/>
<br/>
<?php
if ($_SESSION['current_try']<=$max_tries) // if user has more tries available
{
if(intval($_POST['num'])==$_SESSION['the_magic_number']) // did he found it?
{
echo "You found it! Gongratulations! Click <a href=''>here</a> to try again!";
// oh and do not forget to reset the variables (you found this bug, well done!)
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
else
{
// if he didn't found it, display the status of tries left, and the form to try again
echo "This is your try ".($_SESSION['current_try'])." of ".$max_tries." Good Luck!";
?>
<form method="POST" action="mygame.php">
Please enter any number :
<input type="text" name="num"/>
<input type="hidden" name="tries" value="<?php echo (isset($_POST['tries']))?$_POST['tries']-1:$max_tries; ?>"/>
<input type="submit" name="go"/>
</form>
<span style="color:white;background-color:white;"><?php echo "You bloody cheater! The magic number is ".$_SESSION['the_magic_number'];?></span>
<?php
}
}
else
{
// here we are if no tries left! An empty href to reload the page, and we resetting our variables.
// the_magic_number gets NULL so at the start of script it will be "not set" and will get a mt_rand(0,100) value again
echo "You lost! Sorry! Click <a href=''>here</a> to try again!";
$_SESSION['current_try']=1;
$_SESSION['the_magic_number']=NULL;
}
?>
</body>
</html>
the span at the end is a cheat ;) press ctrl+a to use it !!!
I can't for the life of me find a form that doesn't email the results that you submit.
I'm looking to find a form that I can have users enter simple data that i can then spit back out at them in different arrangements. If they submit First and Last, I'll spit out, amongst other things, FirstLast#domain.com. I'm willing to scrounge the code manually to do this, but I cant find a simple form that would allow me to do this.
Edit: PHP or similar simple languages. I've never touched .NET before.
Form:
<form action="process.php" method="post">
First: <input type="text" name="first" />
Last: <input type="text" name="last" />
<input type="submit" />
</form>
Next page:
<?php
$first = $_POST['first'];
$last = $_POST['last']
echo $first . "." . $last . "#domain.com";
?>
See http://www.w3schools.com/php/php_forms.asp for more examples and explanation
Regardless of how you get it, always remember to never trust user input.
<?php
$sfirst = htmlentities($_POST['first']);
$slast = htmlentities($_POST['last']);
echo $first . "." . $last . "#domain.com";
?>
Also, running a validator on the final result may be helpful. But please don't write your own email address validator.
What language/platform/environment are you working in?
I guess you might be looking for a hosted script or webform (the way that people will host web-to-mail scripts I suppose) but I doubt there would be one out there that does this.
But if you have a specific framework to work in, e.g. PHP or .net, please update the question and let us know which.
Thing that simple doens't even need server-side support.
<form onsubmit="magic(this);return false">
<p><label>First <input name=first/></label>
<p><label>Last <input name=last/></label>
<input type="submit">
<div id="output"></div>
</form>
<script type="text/javascript">
var output = document.getElementById('output');
function toHTML(text)
{
return text.replace(/</g,'<');
}
function magic(form)
{
output.innerHTML = toHTML(form.first.value + form.last.value) + '#domain.com';
}
</script>
If I get your question right, sounds like this might do what you need..
Note: This PHP code doesn't require any knowledge of the fields in the form that submits to it, it just loops through all of the fields, including multiple-choice fields (like checkboxes), and spits out their values.
<?php
// loop through every form field
while( list( $field, $value ) = each( $_POST )) {
// display values
if( is_array( $value )) {
// if checkbox (or other multiple value fields)
while( list( $arrayField, $arrayValue ) = each( $value ) {
echo "<p>" . $arrayValue . "</p>\n";
}
} else {
echo "<p>" . $value . "</p>\n";
}
}
?>