Please note that I am just beginning to learn php. I've gone through a few different multi-day tutorials and I'm now trying to write a small mailing list script on my own. This, I'm sure, is a ridiculously simple question/answer, but no way in which I've figured out how to word the question has turned up any results on google.
i have a checkbox named "htemail", when i send it to the script i have this code:
if(!$_POST['htemail']){
$usehtml = 0;
}else{
$usehtml = 1;
}
echo($usehtml);
if the checkbox is checked, it returns 1, but if it's not I get the following error:
Notice: Undefined index: htemail in C:\wamp\www\mailing list\createUser.php on line 7 Call Stack #TimeMemoryFunctionLocation 10.0004673576{main}( )..\createUser.php:0 0.
The first thing I thought to do was to flip the code around backwards so it checks for the existance of the check first (I'm not sure why I thought this would help)
Thanks in advance for any answers开发者_如何学运维.
The browser might not include in the post data if it's not checked. Use the function isset
to check on it. If is not set, mean it's not checked, the other way around is not true, if set, might still be false.
if(isset($_POST['htemail']) && $_POST['htemail'] == "Value"){ //where "Value" is the
//same string given in the HTML form, as value attribute the the checkbox input
$usehtml = 1;
}else{
$usehtml = 0;
}
As an alternative to isset
you can use array_key_exists
What you want is to detect the existence of the array member, then check it's contents:
$usehtml = 0;
if (isset($_POST['htemail']) && strtolower($_POST['htemail']) == 'yes'){
$usehtml = 1;
}
echo($usehtml);
isset()
checks to make sure the array member exists, in which case you can then check to make sure the value evaluates to your required value.
Additionally, above I've ordered the evaluation to default to a value (0), then change to another value if another variable is present. There really isn't a big difference between doing this and an if/else statement, but I think it's cleaner to read and understand.
精彩评论