dongxian7194 2013-06-13 11:14 采纳率: 0%
浏览 52
已采纳

使用mysqli php将简单的复选框插入数据库

I'm new to PHP. I learnt how to insert data from a textbox but I am facing a problem now when I have to get data from a checkbox. I checked out other posts but they are either too advanced and most of them are using mysql rather than mysqli.

I have ->> two check boxes and a submit button

I would like insert the value of the check box into the database, when selected(one or both).

Thanks

HTML FORM Code:

<html>
<head>

<title>Insert Data</title>
</head>

<body>
<h1> check box testing </h1>


<form name="form1" method="post" action="checkbox_test.php" >
<fieldset>
<legend> Checkbox Trial </legend> 

<h3> Subject selection </h3>
<input type="checkbox" name="PHP" value="php" id="cbsubp1"/> PHP 


<br/>
<input type="checkbox" name="ASP" value="course[]" id="cbsub2"/> ASP.NET 
<br/>
<input type="submit" value="submit" id="submit"/>

</fieldset>


</form>

</body>
</html>

and PHP code is

<html>
<head>

<title>Insert Data</title>
</head>

<body>
<h1> check box testing </h1>

<?php
$con=mysqli_connect("localhost","root","","chkbox");
//check connection
if(mysqli_connect_errno())
{
    echo "Cannot connect to mySQL:".mysqli_connect_error();
}
else
{
    echo "Connected to mySQL succesfully";
}

$query= "INSERT into sub(Subject1) VALUES('$_POST[php]')";
if (!mysqli_query($con,$query))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "record added";
?>
</body>
</html>
  • 写回答

1条回答 默认 最新

  • douliexing2195 2013-06-13 12:23
    关注

    For information:

    If the checkbox is not selected on the form, the field is not sent in the posts array. i.e. the actual fieldname $_POST['PHP'] will not exist.

    You will need to change your code to something like this.

    $subject1 = isset($_POST['php']) ? mysqli_real_escape_string($_POST['php']) : 'DEFAULT_VALUE'; 
    
    $query = "INSERT into sub(Subject1) VALUES('$subject1')";
    $result = mysqli_query($query);
    if ( $result ) {
        echo 'Record Added';
    } else {
        die('Error: ' . mysqli_error($con));
    }
    

    This will insert either the value of the checkbox field or your default value if the checkbox was not selected by the user.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路