我在西湖1 2017-10-04 12:46
浏览 46
已采纳

如果会话变量匹配,则激活按钮

Situation

I have 3 buttons that are designed to be able to switch between different company's.

I have put those buttons in a form:

echo '<form action="?" method="post">';

foreach ($_SESSION['bedrijf'] as $value) { 
   echo '<button type="submit" class="btn btn-default" name="bedrijf_keuze[]" value="bedrijf_keuze_'.$value.'"><img src="images/logo_'.$value.'_small.png" height="40"></button> '; 
} 
echo'</form>';

Thru POST I am using this as an session variable into the rest of the system:

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    foreach($_POST["bedrijf_keuze"] as $key=>$value)
    {
        $bedrijf_keuze = trim(mysqli_real_escape_string($mysqli, $value));
        $_SESSION['bedrijf_keuze'] = $bedrijf_keuze;
    }
}

Now when an button is clicked the form is send and when I echo I see the correct value of $_SESSION['bedrijf_keuze']

To be able to see which company is chosen I have replaced class="btn btn-default" with if($_SESSION['bedrijf_keuze'] == "bedrijf_keuze_'.$value.'") { echo 'class="btn btn-default active"'; } else { echo 'class="btn btn-default"'; }

Problem

The button that is clicked and where the session value is set for is not shown as active. The final code of the form is now:

echo '<form action="?" method="post">';

foreach ($_SESSION['bedrijf'] as $value) 
{ 
   echo '<button type="submit" '; 
   if($_SESSION['bedrijf_keuze'] == "bedrijf_keuze_'.$value.'") { 
       echo 'class="btn btn-default active"'; } 
   else { 
       echo 'class="btn btn-default"'; 
   } 
   echo ' name="bedrijf_keuze[]" value="bedrijf_keuze_'.$value.'"><img src="images/logo_'.$value.'_small.png" height="40"></button> '; 
} 
echo'</form>';

When I echo $_SESSION['bedrijf_keuze'] and bedrijf_keuze_'.$value.' the values are corresponding. So what went wrong and how to solve this?

  • 写回答

1条回答 默认 最新

  • dongzongzhi6953 2017-10-04 13:03
    关注

    The problem you are facing is that you are comparing values that never can correspond.

    "bedrijf_keuze_'.$value.'" != '"bedrijf_keuze_'.$value.'"'

    <kbd>Code</kbd>

    <?php
        $value = 'foo';
    
        echo "bedrijf_keuze_'.$value.'";
        echo '"bedrijf_keuze_'.$value.'"';
    

    <kbd>Output</kbd>

    bedrijf_keuze_'.foo.'
    "bedrijf_keuze_foo"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题