Notice: Undefined index [duplicate]
I have a checkbox which can make a post password protected-
<p><strong><label for="password">Password protect?</label></strong> <input type="checkbox" name="password" id="password" value="1" /></p>
My Php tries to post-
$password = htmlspecialchars(strip_tags($_POST['password']));
I get the undefined index error.
Now, if I try to check first if the password was set, I get the same error executing-
$sql = "INSERT INTO blog (t开发者_运维技巧imestamp,title,entry,password) VALUES ('$timestamp','$title','$entry','$password')";
$result = mysql_query($sql) or print("Can't insert into table blog.<br />" . $sql . "<br />" . mysql_error());
How do I fix it? Do I have to do it for every field like title text box and all?
Why are you stripping tags and escaping a boolean value? You could just do it like this:
$password = (isset($_POST['password']) && $_POST['password'] == 1) ? 1 : 0;
or:
$password = isset($_POST['password']) ? (bool) $_POST['password'] : 0;
You receive the undefined index because your accessing a non-existing array indices.
You should make sure the value is set before setting it:
if (isset($_POST['password'])) {
$password = $_POST['password'];
}
You probably get an undefined variable warning the second time. You can e.g.assure that $password is set regardless of whether _POST[xyz] is set or not.
$password = isset($_POST['password']) ? $_POST['password'] : '0';
see http://docs.php.net/ternary
A checkbox value is only returned if the checkbox is selected. Therefore, if the password checkbox is not selected, the key password
does not exist in the $_POST
array.
You could do:
$password = array_key_exists('password', $_POST) ? '1' : '0';
精彩评论