user5567987 user5567987 - 10 months ago 74
PHP Question

Syntax error. Unexpected 'if'

I want to select one of the genders in the select option when $row["gender"] == select option. The only way to do this i think is through if else statement, but in this case, 'if' creates error. I think my syntax might be wrong or is it because of the single and double quote?

$output .= '
<tr class="datas">
<td class="id" data-id10="'.$row["id"].'" contenteditable>'.$row["id"].'</td>
<td class="firstname" data-id1="'.$row["id"].'" contenteditable>'.$row["firstname"].'</td>
<td class="middlename" data-id2="'.$row["id"].'" contenteditable>'.$row["middlename"].'</td>
<td class="lastname" data-id3="'.$row["id"].'" contenteditable>'.$row["lastname"].'</td>
<td class="address" data-id4="'.$row["id"].'" contenteditable>'.$row["address"].'</td>
<td class="gender" data-id5="'.$row["id"].'" contenteditable>

<select onchange="getval(this)">

'if ($row["gender"]=="Male") {
echo '<option value="Male" selected>Male</option>
<option value="Female">Female</option>';
} else if ($row["gender"]=="Female") {
echo '<option value="Male">Male</option>
<option value="Female" selected>Female</option>';
} .'



<td class="contact" data-id6="'.$row["id"].'" contenteditable>'.$row["contact"].'</td>
<td class="username" data-id7="'.$row["id"].'" contenteditable>'.$row["username"].'</td>
<td class="password" data-id8="'.$row["id"].'" contenteditable>'.$row["password"].'</td>

<td class="but"><button type="button" name="delete_btn" id="delete_btn" data-id9="'.$row["id"].'" class="btn btn-xs btn-danger btn_delete">DELETE</button>
<button type="button" name="delete_btn" id="update_btn" data-id12="'.$row["id"].'">UPDATE</button>

Answer Source

I suggest to rewrite part of Your code like this:

$output = ' ...
<select onchange="getval(this)">
    <option value="Male" ' . ( $row["gender"]=='Male' ? 'selected' : '' ) . '>Male</option>
    <option value="Female" ' . ( $row["gender"]=='Female' ? 'selected' : '' ) . '>Female</option>
</select> ...'

Ternary Operator