Storing checkbox values in sessions and then re-selecting check boxes checked when they came back to add some more

人盡茶涼 提交于 2019-12-13 09:25:42

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!