3

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 (timestamp,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?

Orin Reyes
  • 41
  • 3

4 Answers4

5

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;
Tomas Markauskas
  • 11,496
  • 2
  • 33
  • 35
1

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

VolkerK
  • 95,432
  • 20
  • 163
  • 226
1

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'];
}
Anthony Forloney
  • 90,123
  • 14
  • 117
  • 115
0

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';
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143