开发者

PHP - checkbox value / db insert and if(isset())

开发者 https://www.devze.com 2023-03-26 08:32 出处:网络
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:) )

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.


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.


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.


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']);


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.


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;


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


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

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

$live = 1;
}else{
$live = 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') ";


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;
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消