Skip to main content Jump to list of all articles

Getting to grips with PHP Checkboxes

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
//database server
define('DB_SERVER', "localhost");
 
//database login name
define('DB_USER', "your login name");
 
//database login password
define('DB_PASS', "Your MYSQL PASSWORD");
 
//database name
define('DB_DATABASE', "Your Database");
 
//smart to define your table names also
//define('TABLE_USERS', "");
//define('TABLE_NEWS', "");
?>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Database setup</title>
</head>
<body>
<h1>Setup</h1>
<?php if (!isset($_POST['submit'])) { ?>
			<form name="setup" action="<?php $_SERVER['PHP_SELF']?>" method="post">
    				<input type="submit" value="Setup" name="submit" />
			</form>
<?php 
			} 
	else
    		{
			require ('Database.class.php');
			$db->connect();
			$query= "CREATE TABLE IF NOT EXISTS options(
			id int(1) NOT NULL auto_increment,
			checkbox ENUM('Y','N') NOT NULL DEFAULT 'N',
			primary key (id))";
			$db->query($query);

			$data['id'] = '';
			$data['checkbox'] = 'N';
			$success=$db->query_insert("options",$data);

			if ($success)
				{
    				$myFile = "setup.php";
    				unlink($myFile);
    				header('Location: ../index.php');
				}		

   	 }?>
</body>
</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.

Checkboxes

<?php
                include('lib/Database.class.php');
                $db->connect();
                $query = "SELECT checkbox from options WHERE id='1'";
                $result = $db->query_first($query);
                $checkbox = $result['checkbox'];
                    if ($checkbox == 'Y')
                        {
                            $selected='checked="checked"';
                            $value='Y';
                        }
                        else
                            {
                            $selected='';
                            $value='N';
                            }
 
?>

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 if (isset ($_POST['submitted']))
            {
                if (isset($_POST['flowers'])== 'Y')
                    {
                        $value='Y';
                     }
                else {
                        $value='N';
                     }
 
                 $data['checkbox']= $value;
                 $db->query_update("options",$data, "id='1'");
                 $db->close();
                 header('Location: index.php');
 
}?>

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.

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

Download

6 replies on “Getting to grips with PHP Checkboxes”

Avatar of Lloyd

Thank you for this helpful tutorial. Ive been trying to add more checkboxes to this (named this one checkbox1 and added checkbox2, checkbox3, checkbox4 to the table). But I cannot seem to get it to work. Could you shed any light on that perhaps?

Avatar of Tracy Ridge

Hi Lloyd. It could have something to do with only fetching the first row (id) in the database as I only used 1 checkbox I only needed one row so it was relatively easy to fetch. To change you could alter the database to fetch all the rows. As there are multiple checkboxes it might be better to get the values sent as as array. I’ll have a play and report my findings.

Avatar of Lloyd

Thank you Tracy! I’m still fiddling with it myself but it doesnt seem to get me anywhere 🙁
Looking forward to your findings 🙂

Avatar of Jimmy

I wanted to thank you a large amount more for this amazing
web-site you have created here. It truly is full of useful tips for those who have
been genuinely interested in this subject, specifically this very post.
Your all actually sweet plus thoughtful of others because well
as reading your site posts is a wonderful delight in my experience.

And what a generous reward! Mary and I will certainly have fun making use of
your guidelines in what we must do in a couple of weeks.
Our checklist is mostly a mile long which means that your tips might be put to great use.

Comments are closed.