Skip to main content Jump to list of all articles

Getting to grips with PHP Checkboxes

Published on by Tracy Ridge in

The aim of this tutorial is simply to get the data from PHP checkboxes and store it in an MYSQL database and on page load, the data is retrieved from the database and is shown which would be suitable for an options page in a PHP script. This script has now been included in wow playground with new and updated features.

Prerequisites

I am assuming that you have access to a PHP web server and have an MYSQL database. I highly recommend Xampp for your testing needs. I am also assuming that you know the basics of uploading and using an FTP program and have the use of a text editor or IDE.

Database Setup

When it comes to the database I like the simpler things in life so I use an MYSQL class from Ricocheting.com. This will be included within the script which you can download from the bottom of this post. Unzip the download file and upload it to your server. As you can see the checkbox_demo folder has 1 file and 1 folder containing 3 files. Inside the lib folder, there is the Database.class.php, config.php and setup.php and in the root folder, there is index.php. First and foremost you need to open config.php and put your database settings in the appropriate places and save.

PHP
 1<?php
 2//database server
 3define('DB_SERVER', "localhost");
 4
 5//database login name
 6define('DB_USER', "your login name");
 7
 8//database login password
 9define('DB_PASS', "Your MYSQL PASSWORD");
10
11//database name
12define('DB_DATABASE', "Your Database");
13
14//smart to define your table names also
15//define('TABLE_USERS', "");
16//define('TABLE_NEWS', "");
17?>

Now navigate to lib/setup.php with your browser. Below is the source of the setup file to give you an understanding.

Setup – PHP Checkboxes

PHP
 1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2<html xmlns="https://www.w3.org/1999/xhtml">
 3<head>
 4<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5<title>Database setup</title>
 6</head>
 7<body>
 8<h1>Setup</h1>
 9<?php if (!isset($_POST['submit'])) { ?>
10           <form name="setup" action="<?php $_SERVER['PHP_SELF']?>" method="post">
11                   <input type="submit" value="Setup" name="submit" />
12           </form>
13<?php
14           }
15   else
16           {
17           require ('Database.class.php');
18           $db->connect();
19           $query= "CREATE TABLE IF NOT EXISTS options(
20           id int(1) NOT NULL auto_increment,
21           checkbox ENUM('Y','N') NOT NULL DEFAULT 'N',
22           primary key (id))";
23           $db->query($query);
24
25           $data['id'] = '';
26           $data['checkbox'] = 'N';
27           $success=$db->query_insert("options",$data);
28
29           if ($success)
30               {
31                   $myFile = "setup.php";
32                   unlink($myFile);
33                   header('Location: ../index.php');
34               }
35
36}?>
37
38</body>
39</html>

Setup.php is a basic form when the user clicks on the setup button the script creates the table called options within your database, then creates the checkbox column which is of type enum, a string that can only take 1 set of allowed values, in my case ‘Y’ or ‘N’. Then it adds data to the database, deletes the setup file and then re-directs you to index.php.

PHP
 1<?php
 2include('lib/Database.class.php');
 3$db->connect();
 4                $query = "SELECT checkbox from options WHERE id='1'";
 5                $result = $db->query_first($query);
 6$checkbox = $result['checkbox'];
 7                    if ($checkbox == 'Y')
 8{
 9$selected='checked="checked"';
10$value='Y';
11}
12else
13{
14$selected='';
15$value='N';
16}
17
18?>

Now as for index.php which I have split into 3 parts. The opening lines connect, query and select the value of the checkbox from the database. It stores the value of the checkbox to the variable $checkbox and then it checks to see if the value of the checkbox is ‘Y’ or ‘N’. If it is ‘Y’ then the variable $value is given a ‘Y’ and the variable $selected is then given ‘checked=”checked”‘. This is then passed on to the form which will tick the checkbox and set the value of the checkbox to ‘Y’.

PHP
 1<?php if (isset ($_POST['submitted']))
 2 {
 3                if (isset($\_POST['flowers'])== 'Y')
 4{
 5$value='Y';
 6}
 7else {
 8$value='N';
 9}
10
11                 $data['checkbox']= $value;
12                 $db->query_update("options",$data, "id='1'");
13                 $db->close();
14                 header('Location: index.php');
15
16}?>

The second part deals with saving the data to the database. First, it checks to see if the hidden field has been submitted then it checks to see if the form flowers value is ‘Y’ or ‘N’. if it is ‘Y’ the $value variable is set to ‘Y’ and then the database is updated accordingly with the correct values and the page is told to refresh.

HTML
 1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
 3    <head>
 4        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 5        <title>Simple Checkbox Test</title>
 6    </head>
 7    <body>
 8        <form action="<?php $_SERVER['PHP_SELF']?>" method="post">
 9                    <label title="flowers" for="flowers"> Do you like flowers? </label>
10                    <input type="checkbox" name="flowers" value="<?php echo $value ?>" <?php print $selected; ?> />
11                    <input type="hidden" name="submitted" value="true" />
12                    <input type="submit" value="ok" name="ok" />
13        </form>
14    </body>
15</html>

As you can see in the 3rd part this is the basic form where the contents of the checkbox are determined by the values that have come from the database or have been changed by user input.

Tags