如何将复选框值保存到MySQL数据库?

时间:2011-08-05 13:22:35

标签: php mysql sql

我有以下html:

<label for="live">Live</label>
<input type="checkbox" name="live" id="live" />

如何使用SQL INSERT将text value of selected = '1' /或text value of unchecked = '0'保存到数据库?

任何建议都非常感谢。

PHP处理html表单(目前'live'是一个输入):

<?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());
    }
    if($link) {
        echo "DB SUCESS <br />";
    }

    //Select database
    $db = mysql_select_db(DB_DATABASE);
    if(!$db) {
        die("Unable to select database");
    }
    if($db){ echo "TABLE SUCCESS<br />"; }

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


        //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) {
        //header("location: ../form/register-success.php");
        echo "Succes";      
        exit();
    }else {
        die("Query failed");
    }
?>

2 个答案:

答案 0 :(得分:7)

<input type="checkbox" name="live" value="1" />Live<br />

^注意值“1”。如果有人检查该框,则它将为1,如果不是,则为NULL。 (不是0!)

在下一页上做一个isset,如果已设置,你很高兴,如果没有,只需将其设置为零。

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

答案 1 :(得分:2)

只有选中的HTML复选框才会在响应中发送值。使用isset