Submit checkbox value to MySQL

Below example states that checkbox values can be stored into MySQL database using PHP program.

Step 1: Create a table in MySQL with following screen shot. (Table name : Booked_Status)
Step 2: Create connection string / configuration page as following example and name it ‘config2.php’
Step 3: Now create a main page called ‘checkbox2mysql.php’ with following code in it.
 <h2>Submit checkbox value to MySQL database in php</h2>
 <form method="post" action="">
Register No: <input type=text name=t1>
 <input type="checkbox" name="chk[]" value="Booked"><label>Booked</label><br/>
 <input type="checkbox" name="chk[]" value="Pending"><label>Pending</label><br/>
 <input type="checkbox" name="chk[]" value="Rejected"><label>Rejected</label><br/>
 <input type="submit" name="submit" Value="submit">

<?php error_reporting (E_ALL ^ E_NOTICE); ?>
include 'config2.php';

$query=mysql_query("select * from booked_status where regno='".$t1."' ") or die(mysql_error());

if (isset($_POST['submit']))
$chkbox = $_POST['chk'];
$i = 0;


$query = "INSERT INTO booked_status (regno, status) VALUES ('$t1','".$chkbox[$i]."')";
mysql_query($query) or die(mysql_error());
echo "<center><h2 style='background-color:green; color:white; display:inline'><span>Successfully updated.</span>";
      echo "<center><h2 style='background-color:red; color:white; display:inline'><span>The Register No. '$t1' is already present in the booking table";
Finally, run the above program and see the following output.
If you run the above program with same Reg Number more than once, it will show following alert message.
That’s all for now! Thank you for referring our blog and don’t forget to share this with others!
Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *