Gadheyan .t.s Gadheyan .t.s - 5 months ago 8x
PHP Question

Using "echo" when assigning string to a variable failing

I am trying to write a php script that takes a value from database and sets it to a dropdown named gender. I have written the following code:

while($row = mysqli_fetch_assoc($result))
$gender = $row['gender'];
$output.= "Gender: <select name='gender'>
<option value='0' ".if ($gender != 'M' || $gender !='F') { echo ('selected="selected"');}.">Select gender</option>
<option value='M' ". if ($gender == 'M') { echo ('selected="selected"');}.">Male</option>
<option value='F' ". if ($gender == 'F') { echo ('selected="selected"');}.">Female</option></select>";

I get a server error because of the echo statement(
echo ('selected="selected"')

The website encountered an error while retrieving http://localhost/search.php. It may be down for maintenance or configured incorrectly.

What is the solution for this?


You could do just a simple comparison function that returns the select string by comparing two parameters:

function selectGender($gender,$out=false)
        // You may not need these 3 lines if $gender is either empty, M, or F //
        $filter = array('M','F');
            $gender = false;

        if($gender == $out)
            return ' selected="selected"'; 

while($row = mysqli_fetch_assoc($result)){ 
    $gender =  $row['gender'];
    $output.= "Gender: <select name='gender'>   
<option value='0'".selectGender($gender).">Select gender</option> 
<option value='M'".selectGender($gender,'M').">Male</option>  
<option value='F'".selectGender($gender,'F').">Female</option></select>";