2

I have a this html:

<option value="yes">Yes</option>
<option value="no">No</option>

and my php:

<?php
exec('uci get sms_gateway.setting.filter',$filt);
echo '<form action='.$_SERVER['PHP_SELF'].' method="post">
<select name="filter">';
foreach ($filt as $value){

if ($filt = "yes"){
    echo '<option value="'.$value.'" selected>Yes</option><br>
          <option value="no">No</option><br>ini yes';}
else {
    echo '<option value="yes">Yes</option><br>
          <option value="'.$value.'" selected>No</option><br> ini no';
}
}
echo '
</select>
<input type="submit" name="submit" value="Submit">';
if(isset($_POST['submit'])){
    {
        $data = $_POST['filter'];
        echo "<br>halo ". $data;
    }
    }
?>

the $filt only has one string it's either yes or no when it's yes I want the yes part on the dropdown menu selected, but when it's no I want the no part on the dropdown selected. How should I do that?

Lin
  • 1,771
  • 6
  • 17
  • 21

2 Answers2

1

This bit of code:

foreach ($filt as $value) you're doing as $value so use:

foreach ($filt as $value){
 if ($value == "yes"){

Then you have 2 sets of braces which are not needed; they're just extra keystrokes for nothing:

if(isset($_POST['submit'])){
    {
        $data = $_POST['filter'];
        echo "<br>halo ". $data;
    }
    } 

Change it to:

if(isset($_POST['submit'])){
        $data = $_POST['filter'];
        echo "<br>halo ". $data;
    }

Another thing I spotted, a missing closing </form> tag.


Just for the record, you were also assigning using a single = sign, instead of comparing using two == for:

if ($filt = "yes")

which theoretically should have read as

if ($filt == "yes")

Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
0

There's many things wrong with your code, you're treating "$filt" as both an array and a value, you're also assigning (=) instead of comparing. I'll give you a working example instead of trying to fix your code:

<?php $possibleValues = array('yes', 'no'); // All possible options ?>
<?php $valueYouWantSelected = 'yes'; // 'yes' will be selected ?>

<select>

    <?php foreach ($possibleValues as $value): ?>

        <?php $selected = ($valueYouWantSelected == $value) ? 'selected' : null; // Select this option if it equals $valueYouWantSelected ?>

        <option value="<?php echo $value;?>" <?php echo $selected; ?>>
            <?php echo $value; ?>
        </option>

    <?php endforeach ?>

</select>

If you're confused about how I assign $selected, check out ternary operators.

Also, I'm using alternative syntax, it makes it easier to organize PHP code within HTML (and colors code properly in your editor).

Community
  • 1
  • 1
Dany Caissy
  • 3,176
  • 15
  • 21