Getting checkbox values on submit

2019-01-01 10:42发布

问题:

I have 6 options, I want to get the checked values to store them in variable on second page. How do I go on doing that?

<form action=\"third.php\" method=\"get\">
    <!-- Choices -->
    Red     <input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Red\">
    Green   <input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Green\">
    Blue    <input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Blue\">
    Cyan    <input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Cyan\">
    Magenta <input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Magenta\">
    Yellow  <input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Yellow\">
    Black   <input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Black\">
    <!-- Submit -->
    <input type=\"submit\" value=\"submit\">
</form>

And third.php page :

$color = $_GET[\'color\'];

echo \'The color is \'.$color;

If I remove [], I get the color is on, when I do it like color[] I get a notice saying :

Array to string conversion

What I want is the value of checked, checkboxes so I can store it in variable.

回答1:

A good method which is a favorite of mine and for many I\'m sure, is to make use of foreach which will output each color you chose, and appear on screen one underneath each other.

When it comes to using checkboxes, you kind of do not have a choice but to use foreach, and that\'s why you only get one value returned from your array.

Here is an example using $_GET. You can however use $_POST and would need to make both directives match in both files in order to work properly.

HTML FORM

<form action=\"third.php\" method=\"get\">
    Red<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"red\">
    Green<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"green\">
    Blue<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"blue\">
    Cyan<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"cyan\">
    Magenta<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Magenta\">
    Yellow<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"yellow\">
    Black<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"black\">
    <input type=\"submit\" value=\"submit\">
</form>

PHP (using $_GET) using third.php as your handler

<?php

$name = $_GET[\'color\'];

// optional
// echo \"You chose the following color(s): <br>\";

foreach ($name as $color){ 
    echo $color.\"<br />\";
}

?>

Assuming having chosen red, green, blue and cyan as colors, will appear like this:

red
green
blue
cyan


OPTION #2

You can also check if a color was chosen. If none are chosen, then a seperate message will appear.

<?php

$name = $_GET[\'color\'];

if (isset($_GET[\'color\'])) {
    echo \"You chose the following color(s): <br>\";

    foreach ($name as $color){
        echo $color.\"<br />\";
    }
} else {
    echo \"You did not choose a color.\";
}

?>

Additional options:

To appear as a list: (<ul></ul> can be replaced by <ol></ol>)

<?php

$name = $_GET[\'color\'];

if (isset($_GET[\'color\'])) {
    echo \"You chose the following color(s): <br>\";
    echo \"<ul>\";
    foreach ($name as $color){
        echo \"<li>\" .$color.\"</li>\";
    }
    echo \"</ul>\";
} else {
    echo \"You did not choose a color.\";
}

?>

Flag: (August the 5th, 2016)

I\'ve received 2 downvotes this morning and my comments we\'re removed; why? Whoever\'s doing this, is obvioulsy doing this with malice. The answer has received nothing but upvotes and now this. I mean seriously; wtf? – Fred -ii- 1 hour ago declined - People are free to vote how they want, as long as you\'re not being targeted. I see no evidence of that. Your comments about votes were noise, flagged as such, and removed.

Answer to this: That\'s just the thing; I am.



回答2:

(It\'s not action=\"get\" or action=\"post\" it\'s method=\"get\" or method=\"post\"

Try to do it using post method:

<form action=\"third.php\" method=\"POST\">
    Red<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"red\">
    Green<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"green\">
    Blue<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"blue\">
    Cyan<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"cyan\">
    Magenta<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Magenta\">
    Yellow<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"yellow\">
    Black<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"black\">
    <input type=\"submit\" value=\"submit\">
</form>

and in third.php

or for a pericular field you colud get value in:

$_POST[\'color\'][0] //for RED
$_POST[\'color\'][1] // for GREEN


回答3:

What i suggest is , its better to use post than get. here are some difference between post VS get

Some notes on GET requests:

  1. GET requests can be cached
  2. GET requests remain in the browser history
  3. GET requests can be bookmarked
  4. GET requests should never be used when dealing with sensitive data
  5. GET requests have length restrictions
  6. GET requests should be used only to retrieve data

Some notes on POST requests:

  1. POST requests are never cached
  2. POST requests do not remain in the browser history
  3. POST requests cannot be bookmarked
  4. POST requests have no restrictions on data length

HTML Code

            <html>
    <head></head>
    <body>
    <form action=\"output.php\" method=\"post\">
    Red<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"red\">
    Green<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"green\">
    Blue<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"blue\">
    Cyan<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"cyan\">
    Magenta<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Magenta\">
    Yellow<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"yellow\">
    Black<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"black\">
    <input type=\"submit\" value=\"submit\">
    </form>
    <body>
    </html>

PHP code

    <?php


    if(isset($_POST[\'color\'])) {
    $name = $_POST[\'color\'];

    echo \"You chose the following color(s): <br>\";
    foreach ($name as $color){
    echo $color.\"<br />\";
    }} // end brace for if(isset

    else {

    echo \"You did not choose a color.\";

    }

    ?>


回答4:

Just for printing you can use as below :

print_r($_GET[\'color\']);

or

var_dump($_GET[\'color\']);


回答5:

I think the value for the $_POST[\'color\'] should be read only after checking if its set.

<?php


    if(isset($_POST[\'color\'])) {
      $name = $_POST[\'color\'];  

    echo \"You chose the following color(s): <br>\";
    foreach ($name as $color){
   echo $color.\"<br />\";
  }} // end brace for if(isset

else {

echo \"You did not choose a color.\";

}

?>


回答6:

Perhaps a better way is using the php function in_array() like this:

$style=\'V\';//can be \'V\'ertical or \'H\'orizontal
$lineBreak=($style==\'V\')?\'<br>\':\'\';
$name=\'colors\';//the name of your options
$Legent=\"Select your $name\";//dress it up in a nice fieldset with a ledgent
$options=array(\'red\',\'green\',\'blue\',\'orange\',\'yellow\',\'white\',\'black\');
$boxes=\'\';//innitiate the list of tickboxes to be generated
if(isset($_REQUEST[\"$name\"])){ 
//we shall use $_REQUEST but $_POST would be better
   $Checked=$_REQUEST[\"$name\"];
}else{
   $Checked=array();
}
foreach($options as $option){
$checkmark=(in_array($option,$Checked))?\'checked\':\'\';
$nameAsArray=$name.\'[]\';//we would like the returned data to be in an array so we end with []
$boxes.=($style==\'V\')?\"<span class=\'label2\' align=\'right\'><b>$option : </b></span>\":\"<b>$option </b>\";
$boxes.=\"<input style=\'width:2em;\' type=\'checkbox\' name=\'$nameAsArray\' id=\'$option\' value=\'$option\' $checkmark >$lineBreak\";
}

echo<<<EOF
<html>
<head></head>
<body>
<form name=\"Update\" method=\"GET\" action=\"{$_SERVER[\'PHP_SELF\']}\">\\n
<fieldset id=\"tickboxes\" style=\"width:25em;\">
<legend>{$Legent}</legend>
{$boxes}
</fieldset>
<button type=\"submit\" >Submit Form</button>
</form>
<body>
</html>
EOF
;

To start with we have created a variable $style to set if we want the options in a horizontal or vertical way. This will infrequence how we display our checkboxes. Next we set the $name for our options, this is needed as a name of the array where we want to keep our options. I have created a loop here to construct each option as given in the array $options, then we check each item if it should be checked in our returned form. I believe this should simplify the way we can reproduce a form with checkboxes.



回答7:

If you want to turn specific values in to new variables if they have been selected:

// Retrieve array color[] and set as variable    
$colors = $_GET[\'color\'];
// Use array_search to find the key for \"red\"
$key_red = array_search(\'red\', $colors);
// If \"red\" exists, the key will be an integer (or FALSE)
if (is_int($key_red)) {
    $red_color = \'Red was selected\';
}


回答8:

foreach is the best way to get array of values.

here the example code: html code:

<form action=\"send.php\" method=\"post\">
    Red<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"red\">
    Green<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"green\">
    Blue<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"blue\">
    Cyan<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"cyan\">
    Magenta<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"Magenta\">
    Yellow<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"yellow\">
    Black<input type=\"checkbox\" name=\"color[]\" id=\"color\" value=\"black\">
    <input type=\"submit\" value=\"submit\">
</form>

phpcode:

<?php

$name = $POST[\'color\'];



foreach ($name as $color){ 
    echo $color.\"<br />\";
}

?>


回答9:

It\'s very simple.

The checkbox field is like an input text. If you don\'t write anything in the field, it will say the field doesn\'t exist.

<form method=\"post\">
    <input type=\"checkbox\" name=\"check\">This is how it works!<br>
    <button type=\"submit\" name=\"submit\">Submit</button>
</form>
<?php
if(isset($_POST[\'submit\'])) {
    if(!isset($_POST[\'check\'])) {
        echo \"Not selected!\";
    }else{
        echo \"Selected!\";
    }
}
?>


回答10:

//retrive check box and gender value
$gender=$row[\'gender\'];
$chkhobby=$row[\'chkhobby\'];
<tr>
    <th>GENDER</th>
    <td>
            Male<input type=\"radio\" name=\"gender\" value=\"1\" <?php echo ($gender== \'1\') ?  \"checked\" : \"\" ;  ?>/>
            Female<input type=\"radio\" name=\"gender\" value=\"0\" <?php echo ($gender== \'0\') ?  \"checked\" : \"\" ;  ?>/>

    </td>
</tr>
<tr>
    <th>Hobbies</th>
    <td>
        <pre><?php //print_r($row);

            $hby = @explode(\",\",$row[\'chkhobby\']);
            //print_r($hby);
        ?></pre>
        read<input id=\"check_1\" type=\"checkbox\" name=\"chkhobby[]\" value=\"read\" <?php if(in_array(\"read\",$hby)){?> checked=\"checked\"<?php }?>>
        write<input id=\"check_2\" type=\"checkbox\" name=\"chkhobby[]\" value=\"write\" <?php if(in_array(\"write\",$hby)){?> checked=\"checked\"<?php }?>>
        play<input id=\"check_4\" type=\"checkbox\" name=\"chkhobby[]\" value=\"play\" <?php if(in_array(\"play\",$hby)){?> checked=\"checked\"<?php }?>>


    </td>
    </tr>
//update
$gender=$_POST[\'gender\'];
$chkhobby = implode(\',\', $_POST[\'chkhobby\']);


标签: php forms