inserting single checkbox values is one thing, but it becomes a whole different ball game when you are trying to insert multiple checkbox values into a table.
My form:
<body> <form method="post" action="chk123.php"> Flights on: <br/> <input type="checkbox" name="Days" value="Daily">Daily<br> <input type="checkbox" name="Days" value="Sunday">Sunday<br> <input type="checkbox" name="Days" value="Monday">Monday<br> <input type="checkbox" name="Days" value="Tuesday">Tuesday <br> <input type="checkbox" name="Days" value="Wednesday">Wednesday<br> <input type="checkbox" name="Days" value="Thursday">Thursday <br> <input type="checkbox" name="Days" value="Friday">Friday<br> <input type="checkbox" name="Days" value="Saturday">Saturday <br> <input type="submit" name="submit" value="submit"> </form> </body> </html>
My php file to read and insert the values into a table:
// Make a MySQL Connection mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("test") or die(mysql_error()); $checkBox = $_POST['Days']; if(isset($_POST['submit'])) { for ($i=0; $i<sizeof($checkBox); $i++) { $query="INSERT INTO example (orange) VALUES ('" . $checkBox[$i] . "')"; mysql_query($query) or die (mysql_error() ); } echo "Complete"; } ?>
But using the code as provided, we can only insert one value and the reason is that the name attribute of checkbox is set to Days in our form. To insert multiple checkbox values, the name attribute should be set to Days[].
Now you will be able to insert as many values as needed because PHP will handle Days as an array. This is how the final PHP code would look like after the necessary modifications:
<body> <form method="post" action="chk123.php"> Flights on: <br/> <input type="checkbox" name="Days[]" value="Daily">Daily<br> <input type="checkbox" name="Days[]" value="Sunday">Sunday<br> <input type="checkbox" name="Days[]" value="Monday">Monday<br> <input type="checkbox" name="Days[]" value="Tuesday">Tuesday <br> <input type="checkbox" name="Days[]" value="Wednesday">Wednesday<br> <input type="checkbox" name="Days[]" value="Thursday">Thursday <br> <input type="checkbox" name="Days[]" value="Friday">Friday<br> <input type="checkbox" name="Days[]" value="Saturday">Saturday <br> <input type="submit" name="submit" value="submit"> </form> </body> </html>
// Make a MySQL Connection mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("test") or die(mysql_error()); $checkBox = implode(',', $_POST['Days']); <br> if(isset($_POST['submit'])) { $query="INSERT INTO example (orange) VALUES ('" . $checkBox . "')"; mysql_query($query) or die (mysql_error() ); echo "Complete"; } ?>
The above is the detailed content of How to Insert Multiple Checkbox Values into a Table with PHP?. For more information, please follow other related articles on the PHP Chinese website!