-1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ster
  • 199
  • 3
  • 14

1 Answers1

2

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

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
  • To expand on this, you were setting the value outside the loop so it never changed. Inside it can work as you want – Machavity Aug 23 '16 at 20:15
  • not work, the result is the same in view-source is: ` ` – ster Aug 23 '16 at 20:21
  • See amended `$row['ID'] == 67` instead of `$row['ID'] = 67` – RiggsFolly Aug 23 '16 at 20:24
  • 'selected="selected"' isn't required, 'selected' will do the job. It's a duplicate of a Q/A I posted a couple of days back... http://stackoverflow.com/questions/39070359/how-to-set-an-option-from-multiple-options-or-array-with-different-values-to-vie and an answer from yesterday http://stackoverflow.com/questions/39071127/build-combobox-with-item-selected 2 votes up in under 10 minutes and not marked as a duplicate by an admin pushes proof to the answer http://stackoverflow.com/questions/38928553/php-allow-user-to-comment-and-rate-only-once-with-their-ip-adress – independent.guru Aug 23 '16 at 20:36
  • It works as just `selected` but the html spec I believe says `selected` is a boolean and therefore should be set to something truthy – RiggsFolly Aug 23 '16 at 20:48
  • You can input selected='yelp', selected='itdoesntreallymatter' or selected='prettymuchwhatyoulike' or simply 'selected' and it will still come out as selected. I've ran it in every browser and it always works. There MAY have been a time when it wasn't true, but it certainly isn't the case anymore. Again, it's still pretty much an exact duplicate of an answer posted yesterday – independent.guru Aug 23 '16 at 21:13