在会话中存储单选按钮值 - PHP

时间:2017-12-28 02:51:32

标签: php session radio-button

如何创建一个带有3个单选按钮的表单和一个单击按钮"提交"并将重新定向到下一页,显示使用会话选择的每个单选按钮的数量。

示例:

  

选择单选按钮A,单选按钮B,单选按钮C

之一      

提交

     

显示下一页,显示所选每个单选按钮的数量,

  • 单选按钮A - 5次
  • 单选按钮B - 2次
  • 单选按钮C - 0次。

到目前为止,我只能使用数据库,如果我想使用会话怎么办?

更新: 我的当前代码只显示我选择的单选按钮

file1.php

session_start();
$_SESSION['choice'] = $choiceVal;

<form method="get" action="file2.php">
    <input type="radio" name="choice" value="R1"> R1<br>
    <input type="radio" name="choice" value="R2"> R2<br>
    <input type="radio" name="choice" value="R3"> R3<br>
    <input type="submit">
</form>

file2.php

session_start();
$choiceVal = $_GET['choice'];
echo "Your registration is: ".$choiceVal.".";

<p><a href="file1.php">Back to main page</a>

2 个答案:

答案 0 :(得分:1)

如果您添加了代码,我将能够添加更详细的答案。

test2.php更改为:

<?php

session_start();

if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = [
    'A' => 0,
    'B' => 0,
    'C' => 0,
  ];
}

$option = isset($_GET['choice']) ? $_GET['choice'] : false;

if ($option) {
  $_SESSION[count][$option]++;
}

echo '<ul>';
foreach ($_SESSION['count'] as $key => $value) {
  echo '<li>Radio Button ' . $key . ' - '. $value .' times.</li>';
}
echo '</ul>';

答案 1 :(得分:0)

您的file2.php代码

<?php 
session_start();
if(isset($_GET['choice'])){//Check the get value.
    if(!isset($_SESSION['click'])){//Check the session exist or not. if not define new array with 0 to all R1,R2,R3.
        $_SESSION['click'] = array('R1'=>0,'R2'=>0,'R3'=>0);
    }
    // Assign the clicked button value to same key's array with +1;
    $_SESSION['click'][$_GET['choice']] = ($_SESSION['click'][$_GET['choice']]+1);
    echo "Your registration is: ".$_SESSION['click'][$_GET['choice']].'<p><a href="q.html">Back to main page</a>';
}
// Print your click count
echo '
<ul>
    <li>Radio Button A - '.$_SESSION['click']['R1'].' times</li>
    <li>Radio Button B - '.$_SESSION['click']['R2'].' times</li>
    <li>Radio Button C - '.$_SESSION['click']['R3'].' times</li>
</ul>';
?>