Solved

checkboxes

Posted on 2011-02-16
20
455 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
20 Comments
 
LVL 9

Expert Comment

by:AriMc
ID: 34911571
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 110

Expert Comment

by:Ray Paseur
ID: 34912313
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 110

Expert Comment

by:Ray Paseur
ID: 34912321
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
Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 34912332
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
ID: 34912347
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 110

Expert Comment

by:Ray Paseur
ID: 34912369
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
ID: 34937068
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 110

Expert Comment

by:Ray Paseur
ID: 34937606
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
ID: 34937793
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
 

Author Comment

by:ian646
ID: 34938206
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 110

Expert Comment

by:Ray Paseur
ID: 34938891
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
ID: 34960167
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 110

Expert Comment

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

Author Comment

by:ian646
ID: 34965352
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 110

Expert Comment

by:Ray Paseur
ID: 34965676
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 110

Expert Comment

by:Ray Paseur
ID: 34965684
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 110

Expert Comment

by:Ray Paseur
ID: 37285321
The response at ID:34912332 covers it, I think.
0
 
LVL 143

Expert Comment

by:Guy Hengel [angelIII / a3]
ID: 37330019
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

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

724 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