JDT |
FREE Downloads |
|
Working with the Checkbox on HTML Forms |
||||
|
Checkboxes are a common component found on many HTML forms, but how can you use them to interact with a MySQL database? Setting up the database fieldIn order to allow the checking (selecting) or unchecking (deselecting) of a checkbox item to be recorded in a database, you need to: a) have a database The following file, which we've called create_field.sql, could be used to create a database called 'test', a table in that database called 'formfields', and a field (in the table) called 'checkbox_form_item'. create_field.sql CREATE DATABASE test; The idea here is that the database field will be set to either 'Y' (to indicate that the checkbox is selected), or 'N' (to indicate that the check is deselected). By default, in other words, the first time the HTML form containing the checkbox is accessed, the checkbox status is set to 'Y' (it is checked). Creating the formIn order to be able to read from and write to the MySQL database table, we'll use a PHP script (form.php), which could typically contain code like that below to connect to the databse table: form.php
<?php Having connected to the database and extracted the data from the 'checkbox_form_item' field (either 'Y' or 'N'), the script carries out a test to see if the data is 'Y', and if it is, checks (selects) the check box. When the user clicks the 'Update Database' button, the form data is passed to the form handler (updateDatabase.php). updateDatabase.php
<?php The script first tests to see if the checkbox has been checked; if it has, the value of the $checkbox_form_item variable is set to 'Y'; if it hasn't, the value of the variable is set to 'N'. The field in the database table is then updated. Go back to MySQL Tutorials home page Go back to Tutorials home page
|
|