Solved

checkboxes

Posted on 2011-02-16
20
438 Views
Last Modified: 2013-12-13
Hi
Help! A beginner having real problems getting my head around checkboxes.  None of my books
deal with checkboxes and the web has given no clear info on this!  I have produced a simple
form which needs checkboxes.
It is needed to log student timetable information (AM/PM sessions).  A user will
tick some/all of the checkboxes which will then be inserted into the relevant column in my mysql table.
i will need to diplay results in HTML  and the user updates the checkboxes if necessary.
thanks for your help on this, it is driving me nuts.
0
Comment
Question by:ian646
20 Comments
 
LVL 9

Expert Comment

by:AriMc
Comment Utility
It's probably just a confusion about the HTML side of checkboxes. Basically you insert them in your PHP-script with code like this:

echo "<LABEL>Use option X: </LABEL>";
echo "<INPUT type=\"checkbox\" name=\"optionx\" value=\"1\"";

if ($optionx==1)
   echo " CHECKED=\"YES\"";

echo ">";

Here the variable $optionx contains zero or one depending on whether you want the checkbox to be initially checked or not.

Then in your receiving PHP-script you can determine the checkbox status like this:

$optionx = $_GET['optionx'];

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
This little script will help you understand them.  Install it and run it to see the moving parts.  Checkboxes that are not checked do not appear in the action script at all (unlike empty input type=text controls).
<?php // RAY_checkbox_test.php
error_reporting(E_ALL);

// IF THE FIELDS HAVE BEEN POSTED
if (!empty($_POST["_submit"]))
{
// CHECK FOR AT LEAST ONE BOX CHECKED - REMOTE THE SUBMIT BUTTON
   unset($_POST["_submit"]);

// IF THE POST ARRAY IS EMPTY NOW, NO BUTTONS WERE CHECKED
   if (empty($_POST))
   {
      echo "YOU DID NOT CHOOSE A CHECKBOX";
   }
   else
   {
      echo "THANK YOU!";
      var_dump($_POST); // SHOW WHAT WAS CHECKED
   }
}
// END OF PHP - PUT UP FORM
?>
<html>
<body>
<form method="POST">
CHECK OR UNCHECK BOXES<br/>
BOX1 <input name="box1" type="checkbox" value="MyBox1" <?php if (isset($_POST["box1"])) echo " checked"; ?> /><br/>
BOX2 <input name="box2" type="checkbox" value="MyBox2" <?php if (isset($_POST["box2"])) echo " checked"; ?> /><br/>
<input type="submit" name="_submit"  value="go" />
</form>
</body>
</html>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Another example that might be worth a look...
<?php // RAY_checkbox_array.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;

// DEMONSTRATE HOW TO SUBMIT CHECKBOXES IN THE FORM OF ARRAYS
// NOTE THAT THE UNCHECKED CHECKBOXES DO NOT COME THROUGH INTO $_POST
// NOTE THAT THE UNNAMED INPUT TAGS DO NOT COME THROUGH INTO $_POST

if (!empty($_POST["godo"]))
{
    // WHICH SUBMIT BUTTON FIRED?
    echo "YOU SUBMITTED {$_POST["godo"]}";
    echo PHP_EOL;
    var_dump($_POST);
}
// END OF PHP - USE HTML AND JAVASCRIPT TO PUT UP THE FORM
?>

<script language="JavaScript">
function toggle(formName, arrayName, YesNo)
{
   var cbox=document.getElementsByName(formName)[0].getElementsByTagName('input');
   for(i=0;i<cbox.length;i++)
   {
      if (cbox[i].name.substr(0,arrayName.length) == arrayName) cbox[i].checked=YesNo;
   }
}
</script>

<form method="post" name="checkForm">
GROUP A - SINGLE CLICK OR SELECT / DESELECT ALL
<input name="abox[1]" type="checkbox" value="A1" /> A1
<input name="abox[X]" type="checkbox" value="AX" /> AX
<input name="abox[3]" type="checkbox" value="A3" /> A3
<input                type="checkbox" onClick="toggle('checkForm', 'abox', this.checked)"> ALL OF 'A' (NO REFERENCE TO ANY OF 'B')

GROUP B - SINGLE CLICK OR SELECT / DESELECT ALL
<input name="bbox[1]" type="checkbox" /> B1
<input name="bbox[2]" type="checkbox" /> B2
<input name="allofB"  type="checkbox" onClick="toggle('checkForm', 'bbox', this.checked)"> ALL OF 'B' (NO REFERENCE TO ANY OF 'A')

GROUP C - SINGLE CLICK ONLY
<input name="cbox[]" type="checkbox" value="One" /> C[]
<input name="cbox[]" type="checkbox" value="Two" /> C[]
<input name="cbox[]" type="checkbox" value="Tre" /> C[]

SOME ADDITIONAL FORM DATA
<input name="thing"   type="text"    value="FOO" />
<input                type="text"    value="BAR" />
<input name="godo"    type="submit"  value="GO" />
<input name="godo"    type="submit"  value="DO" />
</form>

Open in new window

0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
And this.  Please try these examples and post back with any specific questions.  Also, this is a really great book.  Wish I had written it!
http://www.sitepoint.com/books/phpmysql4/
<?php // RAY_checkboxes.php
error_reporting(E_ALL);


// DEMONSTRATE HOW CHECKBOXES WORK IN FORM AND ACTION SCRIPTS


// IF ANYTHING HAS BEEN POSTED, SHOW THE CONTENTS
if (!empty($_POST))
{
   echo "<pre>";
   echo '$_POST CONTAINS:' . PHP_EOL;
   var_dump($_POST);
   echo "</pre> \n";
}
?>
<form method="POST">

These checkboxes have names...<br/>
The first two have values...<br/>
Check or Uncheck Some Boxes Here<br/>
<input name=box1 type="checkbox" value="Box1"><br/>
<input name=box2 type="checkbox" value="Box2"><br/>
<input name=box3 type="checkbox"><br/>
<input name=box4 type="checkbox"><br/>
<br />

These checkboxes are part of the "box" array...<br/>
Check or Uncheck Some Boxes Here<br/>
<input name=box[] type="checkbox" value="ABox1"><br/>
<input name=box[] type="checkbox" value="ABox2"><br/>
<input name=box[] type="checkbox" value="ABox3"><br/>
<input name=box[] type="checkbox" value="ABox4"><br/>
<input type="submit" value="go" />
</form>

<?php
die(highlight_file(__FILE__, TRUE));

Open in new window

0
 

Author Comment

by:ian646
Comment Utility
thank you very much for the feedback.  i will work through your code and let u know how i got on. thanks again
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
I may be away for a while, but I check EE daily.  Try the examples and see what you learn, then post back and I will be glad to help.  Best of luck! ~Ray
0
 

Author Comment

by:ian646
Comment Utility
Hi Ray
i have tried yr first code and it worked.  i imagine instead of var_dump($_POST) i need to use an echo command to display what was checked in HTML?  Also, how would i get those values into my sql database?
thanks
Ian
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
echo, var-dump, and print_r are all ways of visualizing data.  As far as getting values into a data base, I want to ask you to please consider buying that book and reading it.  It teaches things that go in depth beyond what we can do here at EE with a question like that.  The difficulty of answering such a broad and open-ended question is that we do not know what you want to do with the data base, and so our advice is likely to be wrong, or at best ignorant of your particular applications' needs.

http://www.sitepoint.com/books/phpmysql4/

All the best, ~Ray
0
 

Author Comment

by:ian646
Comment Utility
thanks Ray - think i'll buy the book! easy learning text fields etc but books seem to subtley avoid the question of checkboxes and how they manage data.  most websites i visit either avoid the subject or seem to be as confused as i am!
thanks for your help.
ian
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:ian646
Comment Utility
Ray,
I have got the checkboxes working and choices made will now display in HTML as verification to the user  - can you point me in how i save this checkbox data into multiple columns in my dbase?  i can show some of my code if necessary?! also, does this book specifically focus on checkboxes and linkage to sql databses?  I would be mightily disppaointed otherwise!
thanks
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
The book teaches just what its title says.  Checkboxes are about 1/1000 of what you need to know to use HTML, PHP and data bases together.

In the REQUEST array (GET or POST) the value associated with a checked checkbox is present.  The "name" from the HTML form is the index of the $_POST or $_GET array, and the "value" from the form is the value of that position in the array.  With no value given, I believe that most browsers will send "on" and if there is no checkbox with that name checked the array element is not set.

Do you know how to connect, select and update a data base table?  If not, you might want to post a new question about that part of the application.
0
 

Author Comment

by:ian646
Comment Utility
Hi
i got the book and am slowly working my way through it.  i have also bought 2 other books - i seem to have found it difficult to find  a chapter (and examples) which will take a checkbox array and insert the checked data into a sql table!?!
thanks for your help anyway  -  
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Let me try this one again: Do you know how to connect, select and update a data base table?
0
 

Author Comment

by:ian646
Comment Utility
yes  - i am fine with text boxes and radio buttons and have those working in my form.  i have little info on checkboxes  - my books tend to pass checkboxes by!  tried last night using the implode function to post into a column in the table but i couldn't get it to work.  the field remained blank.  i am amazed on the scarcity of info in beginners books. may ask a php expert to finish my project.
sorry for being so dense Ray - i appreciate your help.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Buy that SitePoint book.  Give yourself a month or two to work through the examples.  You won't be "dense" at all after you see the instructions and examples that SitePoint provides.  But don't expect instant gratification - programming does not work that way at all.  This explains why.
http://norvig.com/21-days.html

The script I posted at ID:34912332 is available on my server at http://www.laprbass.com/RAY_checkboxes.php -- if you read the code and try experimenting with different checkboxes there you will be able to see how they work.

Here is another learning resource: http://us3.php.net/tut.php

The problem you face (and we all face as we learn web technologies) is that there is not one subject that can be mastered first.  You have to learn HTML, CSS, PHP, MySQL, principles of user-experience design, JavaScript, jQuery, and web services all at the same time.  To compound that problem, HTML and CSS are designed to fail silently.  You will have hateful little typographical errors and you won't be able to find them.  It can all be very frustrating, and I sympathize with your plight.

Best of luck, ~Ray
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Oops, sorry - I see you already got the book.  Great Start!  Charge ahead and use EE every time you come to something that gives you pause.  There are lots of experts here who know PHP very well and are eager to help.

Cheers!
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
The response at ID:34912332 covers it, I think.
0
 
LVL 142

Expert Comment

by:Guy Hengel [angelIII / a3]
Comment Utility
This question has been classified as abandoned and is closed as part of the Cleanup Program. See the recommendation for more details.
0

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now