Search code examples
phpwhile-loopselected

Selected in option from while PHP


I have a problem to select the preferred value

<?php
...
if ($result->num_rows > 0) {
   $selected_rep = ($row['ID']=67) ? 'selected="selected"' :'';
   while($row = $result->fetch_assoc()) {
    	echo "<option $selected_rep value='". $row["ID"]."'>" . $row["NUME"]. ' '. $row["PRENUME"]. "</option>\n";
   }
}
...
?>

I want to select the value with ID=67. Not function $selected_rep ,select all values.


Solution

  • Simply put the selected test inside the loop where it has access to the loaded $row for each of the resultset rows you are processing

    if ($result->num_rows > 0) {
    
       while($row = $result->fetch_assoc()) {
            $selected_rep = ($row['ID'] == 67) ? 'selected="selected"' :'';
    
            echo "<option $selected_rep value='". $row["ID"]."'>" . $row["NUME"]. ' '. $row["PRENUME"]. "</option>\n";
       }
    }
    

    Ahhh and you write test using == and not =

    == is this equal to that

    = set this to that