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

使用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>

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.