问题
I am trying to pass my checkbox values through a session variable if the user goes back by clicking add more books link. I want to show them previously selected check boxes are checked. I tried in chklist.php page
if(isset($_SESSION['pro'])){
echo $_SESSION['pro'];}
shows values like 1_2_5 which are present in session array. Here is my html code of checkboxes. I have about 24 checkboxes with the same name as product[].
<name="product[]" type="checkbox" value="1" alt="1607.00" />
<name="product[]" type="checkbox" value="2" alt="1607.00" />
and so on Here I am setting my session after POST of checkboxes .
$_SESSION['pro'] = implode('_', $_POST['product']);
in nextpage chkout.php. How to make previously selected checkboxes are checked when user came back to firstpage(chklist.php) by clicking ADD MORE BOOKS link present in chkout.php, can any body write the code what i need add to my html.
回答1:
You can put products array into session then access it as an array.
When setting:
$_SESSION["products"] = $_POST["product"];
When listing products, you should check the values from session:
for($i = 0; $i < 24; $i++) {
echo '<name="product[]" type="checkbox" value="'.$i.'" alt="1607.00"';
if(in_array($i, $_SESSION["products"])) echo ' checked="checked" ';
echo ' />';
}
This is the basic idea and example code.
--UPDATE--
According to your comments:
Inside the form, we will print products as follow:
<?php
session_start();
$session_products = array();
if(array_key_exists("products", $_SESSION))
{
if($_SESSION["products"] != null)
{
$session_products = $_SESSION["products"];
}
}
<form method="post" action="newtest.php">
<input name="product[]" type="checkbox" value="1" <?php if(in_array("1", $session_products)) echo "checked='checked'"; ?> alt="1607.00" />
<input name="product[]" type="checkbox" value="2" <?php if(in_array("2", $session_products)) echo "checked='checked'"; ?> alt="1848.00" />
<input name="product[]" type="checkbox" value="3" <?php if(in_array("3", $session_products])) echo "checked='checked'"; ?> alt="180.00" />
<input name="product[]" type="checkbox" value="4" <?php if(in_array("4", $session_products)) echo "checked='checked'"; ?> alt="650.00" />
and so on upto 24 ...
</form>
Inside the code where the form values are posted, we will put these values into session:
<?php
include("config.php");
session_start();
if(isset($_POST))
{
$_SESSION["products"] = $_POST["product"];
}
?>
来源:https://stackoverflow.com/questions/27561922/storing-checkbox-values-in-sessions-and-then-re-selecting-check-boxes-checked-wh