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.

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

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝