简体   繁体   中英

PHP In an Option Tag

Firstly apologies for asking this as it is quite basic but I just can't seem to get it right. Have searched on here and elsewhere for an answer (and tried various) but there is always an error. Spent too long on this little bit and should really know the answer but here goes:

Ok I have a main php file using an include statement to bring in a drop down menu with the options being populated from a MySQL database. In the file being included I have this while loop which creates the options and works fine:

while ($db_field = mysql_fetch_assoc($result)) {
    $ManList2 = $db_field['categoryName']; 
    echo '<option value="' . $ManList2 . '">' . $ManList2 . '</option>';
}

What I want to add is something like the following in the option tag:

if($search == '$ManList2') { echo 'selected'; }

I just can't seem to get it right in the echo statement.

Any help greatly appreciated.

echo '<option value="'.$ManList2.'" '.($search == $ManList2 ? 'selected' : '').'>'.$ManList2.'</option>'; 

How about something like this:

while ($db_field = mysql_fetch_assoc($result)) {
    $ManList2 = $db_field['categoryName'];

    echo '<option value="' . $ManList2 . '"';

    if($search == '$ManList2') {
        echo ' selected';
    }

    echo '>' . $ManList2 . '</option>'; 
}
echo "<option value='".$ManList2; if($search == '$ManList2'){ echo 'selected'; } echo "'>".$ManList2."</option>"; 

You may try something like this (Assumed your select's name is search )

$search = isset($_POST['search']) ? $_POST['search'] : ''; // or $_GET maybe
$selected = '';
while ( $db_field = mysql_fetch_assoc($result) ) {
    $ManList2 = $db_field['categoryName']; 
    $selected = $search == $ManList2 ? 'selected' : '';
    echo '<option '.$selected.' value="'.$ManList2.'">'.$ManList2.'</option>'; 
}

You could use variables to put into your PHP, like:

while($db_field = mysql_fetch_assoc($result)) {
  $ManList2 = $db_field['categoryName']; 
  $selected = $search === $ManList2 ? "selected='selected'" : '';
  echo "<option value='$ManList2'$selected>$ManList2</option>"; 
}

I don't see what $search does, so this approach may not work. I would use my Library. 库。 It handles this sort of thing for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM