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’
<?php $host="localhost"; $username="root"; $password=""; $dbname="demo"; $con=mysql_connect("$host","$username","$password"); mysql_select_db("$dbname",$con); ?>
Step 3: Now create a main page called ‘checkbox2mysql.php’ with following code in it.
<html> <head> </head> <body> <h2>Submit checkbox value to MySQL database in php</h2> <form method="post" action=""> Register No: <input type=text name=t1> <br> <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"> </form> </body> </html> <?php error_reporting (E_ALL ^ E_NOTICE); ?> <?php include 'config2.php'; $t1=$_POST['t1']; $query=mysql_query("select * from booked_status where regno='".$t1."' ") or die(mysql_error()); $duplicate=mysql_num_rows($query); if (isset($_POST['submit'])) { $chkbox = $_POST['chk']; $i = 0; if($duplicate==0) { While($i<sizeof($chkbox)) { $query = "INSERT INTO booked_status (regno, status) VALUES ('$t1','".$chkbox[$i]."')"; mysql_query($query) or die(mysql_error()); $i++; } echo "<center><h2 style='background-color:green; color:white; display:inline'><span>Successfully updated.</span>"; } else { 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!