0

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?

JON
  • 965
  • 2
  • 10
  • 28
Muiter
  • 1,470
  • 6
  • 26
  • 39

1 Answers1

1

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

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

Code

<?php
    $value = 'foo';

    echo "bedrijf_keuze_'.$value.'";
    echo '"bedrijf_keuze_'.$value.'"';

Output

bedrijf_keuze_'.foo.'
"bedrijf_keuze_foo"
DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • OK, that waas the issue although I still don;t understand why this could be the issue. – Muiter Oct 04 '17 at 13:26
  • be careful with [mixing](https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php) double and single qoutes. The posted value of the button does not contain any single quotes, whereas your condition does because the double quotes arround it – DarkBee Oct 04 '17 at 13:29