Web Development

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

Share
Published by
Tracy Ridge

Recent Posts

Hot New Web Dev – November 2024

Welcome to Hot Web Dev November 2024, featuring the latest technology and web development news.… Read More

3 weeks ago

Hot New Web Dev – October 2024

Welcome to Hot Web Dev October 2024, featuring the latest technology and web development news.… Read More

2 months ago

New Svelte 5 Guessing Game 2024

In this tutorial, you’ll build a fun and interactive guessing game using Svelte 5, the… Read More

3 months ago

Hot New Web Dev – September 2024

Welcome to Hot Web Dev September 2024, featuring the latest technology and web development news.… Read More

3 months ago

New JavaScript Guessing Game 2024

The JavaScript guessing game tutorial is a simple beginner's project. It features modern JavaScript syntax… Read More

3 months ago

Hot Web Dev – 12 Useful Top Tools of 2023

If you have been following the monthly Hot Web Dev magazine you will find the… Read More

3 months ago