【问题标题】:Storing checkbox values in sessions and then re-selecting check boxes checked when they came back to add some more在会话中存储复选框值,然后在它们返回时重新选择复选框以添加更多
【发布时间】:2015-02-18 03:30:10
【问题描述】:

如果用户通过单击添加更多书籍链接返回,我正在尝试通过会话变量传递我的复选框值。我想向他们展示之前选中的复选框已被选中。我在 chklist.php 页面中尝试过

if(isset($_SESSION['pro'])){ 
echo  $_SESSION['pro'];} 

显示会话数组中存在的值,例如 1_2_5。 这是我的复选框的html代码。我有大约 24 个与 product[] 同名的复选框。

<name="product[]"  type="checkbox" value="1" alt="1607.00" />
<name="product[]"  type="checkbox" value="2" alt="1607.00" />

等等 在这里,我在复选框 POST 之后设置我的会话。

$_SESSION['pro'] = implode('_', $_POST['product']); 

在下一页 chkout.php。 当用户通过单击 chkout.php 中的添加更多书籍链接返回首页(chklist.php)时,如何制作先前选择的复选框,任何主体都可以编写我需要添加到我的 html 中的代码。

【问题讨论】:

  • 我没有看到你的代码o_o
  • //等等最多24个复选框,感谢您的快速响应这是我在堆栈溢出中的第一篇文章
  • product 是一个数组,做 $_SESSION['checks'] = $_POST['product'];并在第一页打印它(使用 var_dump 或 print_r),你会看到我认为所有的复选框都被选中
  • 我试过 print_r($_SESSION['checks']);它显示数组( [0] => 12 [1] => 13 [2] => 14 )但未选中复选框你能告诉我我需要写什么来选中复选框

标签: php checkbox


【解决方案1】:

您可以将产品数组放入会话中,然后将其作为数组访问。

设置时:

$_SESSION["products"] = $_POST["product"];

列出产品时,您应该检查会话中的值:

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 ' />';
}

这是基本思想和示例代码。

--更新--

根据您的 cmets:

在表格中,我们将打印产品如下:

<?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>

在表单值发布的代码中,我们会将这些值放入会话中:

<?php 
include("config.php"); 
session_start(); 

if(isset($_POST))
{ 
    $_SESSION["products"] = $_POST["product"];
}
?>

【讨论】:

  • 我在这里复制了你的代码';} }?>
  • 这是我的表单
    等等直到 24
    你能告诉我我需要把旧代码或任何其他我可以用输入字段做的事情
  • @isa 正如你所说,我对表格进行了更改,
  • @ isa 正如你所说,我对表单进行了更改,并且在发布表单值的代码中,当我选中复选框并返回时,我将会话代码现在工作正常通过单击链接 的首页(显示的 pafe 表单)但是,当我第一次打开页面test.php(页面形式存在)它显示注意:未定义索引:产品,警告:in_array()期望参数2为数组,给定null请帮助我。
  • @Nag,请在 test.php 中添加 session_start() 命令。检查上面的代码,我已经更新了。
猜你喜欢
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多