Search code examples
phphtmlselectdropdown

Writing an IF statement in a dynamic dropdown select menu gives ERROR


I want to write an IF statement for a dynamically generated dropdown menu, but I keep getting errors or it doesn't just work, what I am trying to do is compare two variables to see if they match from a data in the database

$loma = "Asokoro";

$row['locales'] is from locality table in the database

$row['locales'] = "Asokoro";

$row['locales'] = "Dutse";

$row['locales'] = "Mari";

$row['locales'] = "Cook";

That means if $loma which is Asokoro matches $row['locales'] = "Asokoro"; select it as the option menu

<select name="checkout_area_name" id="checkout_area_name" required>
    $query = "SELECT * FROM `locality` WHERE state_name = '$hi_state'";
    $sql = mysqli_query($con, $query) or die(mysqli_error($con, $query));
    $r = ' <option value="">Please Choose Locality</option>';
    ?>
    <?php
    while ( $row = mysqli_fetch_assoc($sql)) 
    {
        ?>
        <?php $r = $r . '<option value="'.$loma.'" if ("'.$loma.' == '.$row["locales"].'") selected="selected" >'.$row['locales'].'</option>'; ?>
        <?php
    }
    echo $r;    
    ?>
</select>

I am trying to select the options menu that has $loma and $row['locales'] matching but I keep getting errors or when I console.log, it does not produce the result i want.


Solution

  • You are outputting php script as html markup, try changing your code to:

    <select name="checkout_area_name" id="checkout_area_name" required>
      $query = "SELECT * FROM `locality` WHERE state_name = '$hi_state'"; $sql = mysqli_query($con, $query) or die(mysqli_error($con, $query)); $r = '
      <option value="">Please Choose Locality</option>'; ?>
      <?php
        while ( $row = mysqli_fetch_assoc($sql)) 
        {
          $r = $r . '<option value="'.$loma.'" '.(($loma==$row["locales"])?'selected':'').'>'.$row['locales'].'</option>';
        }
        echo $r;    
        ?>
    </select>