Drew
Drew

Reputation: 6862

PHP Select form and if option matches something then make it selected

I have a query like this:

while($stmt->fetch()){
    echo "<option value=\"".$sku_brandname."\">".$sku_brandname."</option>";
}

What I need to do is create a statement that says if sku_brandname = "Something" then make that one selected.

I'm not sure how to do that, because I can't create an if statement in the echo.

I tried something like this:

if($sku_brandname = "$brand") {
    $selected = " selected";
}

but can't quite get it to work, it shows all of them selected.

Upvotes: 0

Views: 235

Answers (2)

Ole
Ole

Reputation: 794

Or you can make it in one line like this. I don't remember exactly what that statement is called

while($stmt->fetch()){
  $selected = ($sku_bandname == 'Something') ? ' selected="selected"' : '';
  echo '<option value="{$sku_brandname}" {$selected} >{$sku_brandname}</option>';
}

Upvotes: 1

P. R. Ribeiro
P. R. Ribeiro

Reputation: 3029

Something like the following should do the job.

while($stmt->fetch()){
  if($sku_bandname == 'Something')
    $selected = ' selected="selected" ';
  else
    $selected = '';
  echo '<option value="{$sku_brandname}" {$selected} >{$sku_brandname}</option>';
}

Upvotes: 0

Related Questions