Reputation: 111
I am trying to evaluate date[3] to determine selected option. All this is inside a php sql query. I am not able to find out an easy way to get a selected for the value returned in date[3] in my $options string variable.
<?php //sql statement
foreach( $db->query($sql) as $data ) {
$options = "<select type='text' name='pagephone' select id='pagephone' >
<option value=''></option>
<option ". if ($data[3] == 'vtext.com' ){ echo 'selected' };. " value='vtext.com'>Verizon Wireless</option>
<option ". if ($data[3] == 'vmobl.com' ){ echo 'selected' };. " value='vmobl.com'>Virgin Mobile</option>
<option ". if ($data[3] == 'sms.alltelwireless.com' ){ echo 'selected' };. " value='sms.alltelwireless.com'>Alltel</option>";
?>
Upvotes: 0
Views: 4352
Reputation: 41810
You're trying to concatenate a value with .
, so the value you use needs to be an expression that evaluates to a string. An if
block is not such an expression, as you can see from the syntax error you get if you use the code from your question. You can use a ternary expression instead, like this.
...<option ". ($data[3] == 'vtext.com') ? 'selected' : '' . " value='vtext.com'>
Verizon Wireless</option>...
Personally, I would prefer to iterate an array of value/text pairs rather than hardcoding all the select options, like this:
$values = [
'vtext.com' => 'Verizon Wireless',
'vmobl.com' => 'Virgin Mobile',
'sms.alltelwireless.com' => 'Alltel'
];
foreach( $db->query($sql) as $data ) {
$options = "<select type='text' name='pagephone' id='pagephone'><option value=''></option>";
foreach ($values as $value => $text) {
$selected = ($data[3] == $value) ? 'selected' : '';
$options .= "<option value='$value' $selected>$text</option>";
}
$options .= '</select>';
}
But that's just my opinion. Don't forget to close your <select>
, though.
Upvotes: 2