Altering PHP Variable Based Off Selection

29 views Asked by At

I have a html select that holds values for all four of our offices, or the text All. If the user selects All, I want to echo "All Offices", but if the user selects a specific office, I want to echo that number. My problem is that when I run the syntax below, All remains All instead of All Offices.

Did I set this up the incorrect way?

Display Data For Which Office:
<select name="office">
    <option value="All">All...</option>
    <option value="one">One Quarter</option>
    <option value="two">Two Quarter</option>
    <option value="three">Three Quarter</option>
    <option value="four">Four Quarter</option>
</select>


<?php
    if ($officename != 'All') {
        $officename = $_POST['officename'];
    } else {
        $officename = "All Offices";
    }

    echo $officename;
?>
2

There are 2 answers

0
anandsun On BEST ANSWER

You never initialized the $officename variable, so it should be null. As a result, won't $officename != 'All' always be true, so $officename = $_POST['officename']; will always be executed?

I think what you want instead is something like:

$officename = $_POST['officename'];

if ($officename == 'All') {
    $officename = "All Offices";
}

echo $officename;
0
ADyson On

I assume you're wanting "All" to come from the value of the <select>, which is named "office". Therefore you need to assign that value to a variable before you can use it for comparison. Note the select is named "office" not "officename", so it's "office" you need to look for in $_POST.

$officeValue = $_POST['office'];

if ($officeValue == 'All') {
    $officename = "All Offices";
}
else {
  $officename = $_POST["officename"]; //I assume this is some other field in the form which you haven't shown, but which contains a human-readable office name.
}

echo $officename;