Radio buttons/checkboxes

Hi there,

I’ve been building a web survey for the past few days. All the text fields and drop-down selectors work fine. However, I’ve not been able to get my radio buttons or checkboxes working properly. I’ve tried all sorts of PHP scripting but I keep on encountering all sorts of errors, so I’ve decided to totally start from scratch.

Your help in creating a new script would be greatly appreciated.

The first part of the code needs to be some sort of loop statement, to create the radio buttons/checkboxes. Coding them individually would be time consuming so I want to avoid doing this. The code needs to make it clear which buttons have been selected, so that they stay selected following $_POST.

<input type="checkbox" class="checkbox" name="example"><br />

The second part of the code then needs to collect the values from the radio buttons/checkboxes and turn this into a variable so that I can convert it into session data. Preferrably I’d prefer this to be done as a string, as I’m not 100% familiar with arrays.

Thanks

It really depends on the use and if you’re dealing with multiple check boxes or radio buttons per-row or over a span of rows. Generally speaking, If they are checkboxes You would make your names arrays like you did in your other post with the value. You can force a name array key with a record id, e.g. name=“item[$id]” and the value which represents the selection or have an open name, e.g. name=“item” and then the value would be the id. How it’s handled on processing again depends on the setup and the result you are looking for. It also depends on if you are inserting records or updating records as only selected checkboxes will be passed. So if you for example updating a table of items to be shown you may need to update all records to NOT shown (0 or false or whatever you are using) then loop through the posted values and mark those records as shown. In most cases you are going to be dealing with arrays and I gave you a few examples on handling post and saving to session. If you can provide an example and explanation of expected results I’m sure someone can provide an answer.

Hi there Drummin,

I’ve scrapped the code that you saw in my previous post because I was struggling with getting it to work properly. Every time I checked to see what data was being posted to the session, it came out as an array. I wanted it to be a string - something like a basic “Yes” or “No” for if something has been selected.

I want the user to be able to select multiple checkboxes/radio buttons. So let’s say the question is “which of the following have you used” and there could be 8 different options. Whilst I don’t want the output to be an array, I still want to use an array to create these form elements as it’ll save time. This is what I had previously.

  foreach($outsourceArray AS $key => $value) {
    $checked = (isset($_POST['outsource']) && is_array($_POST['outsource']) && in_array($key, $_POST['outsource'])) ? 'checked' : '' ;
    $optionOutput .= '<input type="checkbox" class="checkbox" name="outsource[' . $key .']" value="'. $key .'" '. $checked .'>'. $value .'<br />';
  }

I then want to create some simple code like if(isset($_POST[‘outsource’])) to do some basic validation and then store the output to a session. However, I want to make sure the output is as a string, not an array.

Your help would be appreciated :slight_smile:

EDIT: Obviously if I have to use arrays then I will but it’d be great if someone could comment the code to explain exactly how it works :slight_smile:

Well then wouldn’t the second example work for this? Session is always an array with a key and value.

 <?php
session_start();
                                      
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if(isset($_POST['outsource'])){
        foreach($_POST['outsource'] as $outsource){
            $varname = "outsource" . $outsource;            
                $_SESSION[$varname] = $outsource;
        }        
        //echo "<pre>";
        //print_r($_SESSION);
        //echo "</pre>";
    }
}
?> 

Sorry, I must only have tried the first example. I remember the page showing something like this…

      [0] => 1
            [1] => 2
            [2] => 4
            [3] => 3

…which left me confused as to why the data was formatted like that. I’ve just tried your second example and it seems to be more appropriate for what I need.

    [outsource1] => 1
    [outsource5] => 5
    [outsource7] => 7
    [outsource3] => 3

However, I see the index number is displaying as opposed to a yes/no, or True or False. Is that easy to change?

PS: Are there any tutorials you can recommend on arrays and using the data from them? I feel like this is an area of PHP that I need to improve on.

Thanks for your help :smiley:

It would be much easier seeing a row of input fields and giving you an example, however you will notice that only selected checkboxes are passed on POST so those all will be true. So the line where session is set could be changed to “true” if you wish.

$_SESSION[$varname] = "true";

As I mentioned above, sometimes you need to update your table, setting all values to false, then process the posted values as true. There are so many ways to do things and here is a different approach where “items” are looped through while building the form AND during processing as well so you have ALL items at process time regardless of what’s selected and can be set to true or false for each item.

<?php
session_start();	
echo "<pre>";
print_r($_POST);	  
echo "</pre>";

$balls = array("Baseball","Basket Ball","Tennis Ball","Foot Ball");
                                      
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if(isset($_POST['ball'])){	
        foreach($balls as $ball){
		      	$value = (in_array($ball,$_POST['ball']) ? "True" : "False");
               // $_SESSION[$ball] = $value;
                $result[$ball] = $value;
        }        
        echo "<pre>";
        print_r($result);
        echo "</pre>";
    }
}


	$display = '<form action="" method="post">';
		foreach($balls as $ball){
			$display .= "<input type=\\"checkbox\\" name=\\"ball[]\\" value=\\"$ball\\">$ball &nbsp;\\r";  
		}
	$display .= "<br />";
	$display .= '<input type="submit" name="submit" value="Submit" />';
	$display .= '</form>';
?> 
<html>
	<body>
	<?php	
		echo $display;
	?>
	</body>
</html>

You can essentially set it to whatever term you want but it will be generally easier if you use 1/0 or true/false and then ran the item as a boolean for sanitation purposes. It also has the added benefits of you not having to run it through a comparison in an if as you could simply just call the variable itself and it will output a boolean true/false result, something that will also be effective in the ternary operators used in the above example. In that case all you’d need to do is have a default variable set to false and then just set that variable in the loop to $value, or, alternatively, run it through a simple if/ternary check. Something simple like, which will force any $value it’s run against to be either true or false and as such shouldn’t be used outside of an if $key = specific key name unless you want to change all of the values:

$value = ($value !=True)?False:True;

(the above is essentially the same solution used in post 6 but I’d generally recommend not adding a loop if you don’t have to and would personally run this check in the loop that outputs the content itself as initializing loops is somewhat more intensive, so far as I understand it, than just adding to the stuff an existing loop already does particularly when they’re functionally the exact same loop)
or

IF($value !=True){
     $value = False;
}else{
     $value = True;
}

Additionally the reason you’re getting a number is in your html you’re setting the value as the key instead of as True, that’s the red section in the code. The value there can be whatever you want, it need not be $key, and actually probably should not be key, I’d image it should actually be $value since that would provide the value already assigned to that array if checked instead of manually changing it each time to key regardless of what the original or intended value is.

 foreach($outsourceArray AS $key => $value) {
    $checked = (isset($_POST['outsource']) && is_array($_POST['outsource']) && in_array($key, $_POST['outsource'])) ? 'checked' : '' ;
    $optionOutput .= '<input type="checkbox" class="checkbox" name="outsource[' . $key .']" value=[COLOR="#FF0000"]"'. $key .'"[/COLOR] '. $checked .'>'. $value .'<br />';
  }

Additionally if the whole array is run through empty() you can assign it default values if it returns true. Which means you’ll be able to act in a certain way if there is no active session.

Here’s one quick tutorial on arrays I found with a google search, most of what you’re seeing here is looping through an array as a method of handling the data in them. Most PHP books will contain a number of sections just dedicated to looping through arrays in addition to a number of sections to the defining of arrays and I’m sure sitepoint has some offerings in the books/ebooks section that would be useful, particularly since it’s an easy topic to get lost in while new and having constant reference like that around will be helpful. For starters you’ll want to think of it as a way of tabling data with multidimensional arrays being tables storing tables (since that’s essentially all an array is, a not an actual database temporary table which roughly resembles what a database table would in, say, phpMyAdmin on a cpanel server). Sessions are essentially arrays that are slightly less temporary than an array but slightly more temporary than a database so taking the time to learn about arrays will be extremely helpful in learning both session and database management (as those are basically permanent arrays and return results in the same way arrays do).

Thank you both for your help. Not only have I managed to get the problem fixed, but I’ve learnt a bit more about PHP in the process. Thanks :smiley: