2

I'm new to PHP, and I have stumble on the problem which I don't know how to solve. I'm 99% it is due my poor knowledge of PHP ( I'm PHP user since last Monday:) )

Just in front I will declarate that:

  • db conncetion is working
  • table does exist
  • values are saved correctly to the db

I have following form:

<form id="loginForm" name="loginForm" method="post" action="../exe/news-exec.php">
      <input name="live" type="checkbox" class="textfield" id="live" />
      <input name="content" type="text" class="textfield" id="content" />
      <input type="submit" name="Submit" value="Register" />
</form>

And following file is executing this:

<?php
    //Start session
    session_start();

    //Include database connection details
    require_once('../inc/config.php');

    //Connect to mysql server
    $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
    if(!$link) {
        die('Failed to connect to server: ' . mysql_error());
    }

    //Select database
    $db = mysql_select_db(DB_DATABASE);
    if(!$db) {
        die("Unable to select database");
    }

    //Function to sanitize values received from the form. Prevents SQL injection
    function clean($str) {
        $str = @trim($str);
        if(get_magic_quotes_gpc()) {
            $str = stripslashes($str);
        }
        return mysql_real_escape_string($str);
    }

    //Sanitize the POST values
    $live = clean($_POST['live']);
    $content = clean($_POST['content']);



    if(isset($live)) { $live = 1;}
    if(!isset($live)) { $live = 0;}



    //Create INSERT query
    $qry = "INSERT INTO news(live, content) VALUES('$live','$content') ";
    $result = @mysql_query($qry);

    //Check whether the query was successful or not
    if($result) {
        echo $live."<br /><br />";
        echo '<a href="../">Index File</a>';

        exit();
    }else {
        die("Query failed");
    }
?>

What the form should do:

  • if the checkbox is checked - save the value of '1' into field 'live' in the table 'news'
  • if the checkbox is NOT checked - save the value of '0'

If the checkbox has been checked everything is working fine, but if the checkbox is not checked (should echo $live = 0 ), but is displaying value = 1 and following notice: Notice: Undefined index: live in C:\wamp\www\exe\news-exec.php on line 30

Line 30: $live = clean($_POST['live']);

I'm 99% sure the problem are those declaration:

if(isset($live)) { $live = 1;}

if(!isset($live)) { $live = 0;}

What I'm doing wrong? Any suggestion much appreciated.

6
  • Whatif you use: if(isset($live)) { $live = 1;} else{ $live = 0;} Commented Aug 8, 2011 at 7:53
  • @AlphaMale - this is exactly the same as my example - is it not? Commented Aug 8, 2011 at 7:55
  • Try to debug it yourself - use this code echo "<pre>"; var_dump($variable); echo "</pre>"; to print out variable values at different places in code. You will find the answer fast. Commented Aug 8, 2011 at 7:56
  • @Tomas Telensky - ok, so it is telling me that when the checkbox is not checked - value is empty, should if(!isset($live)) { $live = 0;} work with this? Commented Aug 8, 2011 at 8:01
  • $live = clean($_POST['live']); $live is always set here Use $live=(int)isset($_POST['live']); Commented Aug 8, 2011 at 8:12

9 Answers 9

3

HTML:

<input type="hidden" name="live" class="textfield" id="live0" value="0" /> 
<input type="checkbox" name="live" class="textfield" id="live1" value="1" />

PHP:

$live = clean($_POST['live']);

What happens here is that when the checkbox is left unchecked, the hidden field’s value gets submitted, as-is. When the check box is checked, the hidden field’s POST value gets overwritten by the activated checkbox’s.

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

if (isset($_POST['live'])) $live=1; else $live=0;

Line 30: $live = clean($_POST['live']); causes isset($live) to be true, no matter if $_POST['live'] is set or not, so you have to check $_POST['live'] directly.

Comments

2

According to the HTML specs, checkboxes are not sent to the server unless they are checked. You can see the exact contents of $_POST with the var_dump() function.

There are many ways to deal with this. Since you are not assigning a value attribute, I guess the value is irrelevant so you can do this:

// $live is now a boolean
$live = isset($_POST['live']);

3 Comments

My suggestion would be to have value for all the input elements. I really do not have a solid proof to prove my point but it really helps in JS as well as server side.
@Álvaro G. Vicario - where should that be placed in my code to affect my if statement? Just before it?
@NewUser, this should replace the line of code that's triggering a notice.
2

First of all you don't need to clean a variable that's existance is used as a flag. You get the error message because in the case the checkbox is not checked $_POST['live'] doesn't even exist.

$live = (isset($_POST['live']))?1:0;

Should indeed do the trick. Just for some practice with the ternary operator.

3 Comments

Does work perfectly - could you explain what does this statement means exactly?
The clean() function returns an empty string, which isn't the same as the value NULL. Therefor you need to isset() the $_POST value, before configuring it. If you want to check if the value is empty in any way, use empty(). It returns TRUE upon NULL, empty string and 0. In this case you would write if (!empty($live)) { $live = 1; } .
The ternary operator works like a if/else statement $var = <condition> ? value1 : value2 . Condition is evaluated if it's true $var becomes value1 else value2.
1

When you don't check the checkbox, $_POST["live"] is not set, that's why you get the error.

You should try something like:

$live = isset($_POST["live"]) ? 1 : 0;

Comments

0

To check Checkbox checked or not do the following :

<input name="live" type="checkbox" class="textfield" id="live" value="Yes" />

if(isset($_POST['live']) && $_POST['live'] == 'Yes')
 {
      $live = 1;
 }
else
{
      $live = 0;
}  

and check the query

Comments

0
<input name="live" type="checkbox" value="Yes" class="textfield" id="live" />

if(isset($live) && $live == 'Yes'){

$live = 1;
}else{
$live = 0;
}

Comments

0

As well as the examples given here, you might want to check the data type you've set on the DB column for "live". You're passing it as a string, but if you've set it as an INT you don't need the quotes around the value in the INSERT

$qry = "INSERT INTO news(live, content) VALUES($live,'$content') ";

Comments

0

Same with PDO

<?php
//Start session
session_start();

//Include database connection details
require_once('../inc/config.php');

/*** pdo connect ***/
$dbh = new PDO("mysql:host=$hostname;dbname=YOURDB", $username, $password);

/*** prepare the SQL statement ***/
$stmt = $dbh->prepare("INSERT INTO news(live, content) VALUES(:checkbox,:textbox)");

if(isset($_POST)){

    $live = $_POST['live'];
    $content = $_POST['content'];

    try {
        /*** bind the paramaters ***/
        $stmt->bindParam(':checkbox', $live, PDO::PARAM_INT);
        $stmt->bindParam(':textbox', $content);

        /*** execute the prepared statement ***/
        $stmt->execute();

        echo "Query successful ".$live."<br /><br />";
        echo '<a href="../">Index File</a>';

    }catch(PDOException $e){
        die("Query failed");
    }
}else{
    ?>
<form id="loginForm" name="loginForm" method="post" action="../exe/news-exec.php">
      <input name="live" type="checkbox" value="1" class="textfield" id="live" />
      <input name="content" type="text" value="" class="textfield" id="content" />
      <input type="submit" name="Submit" value="Register" />
</form>
<?php
}
/*db finnish*/
$dbh = null;
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.