Search code examples
phphtmlmysqlselected

Echo selected when a variable is equal to another in a select built by PHP and MySQL


Hy Guys, I need a little help with this script: I want to echo selected in a PHP and MySQL built selector. This is my actual code

<?php
    $mysqli = new mysqli('localhost','*****','thisisapassword','****');
    if ($mysqli->connect_error) {
           die('Errore : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
    }


      // CREATE QUERY STRING
    $sql = "SELECT sede_ID, provincia, indirizzo FROM sedi ORDER BY sede_ID, provincia";
      // RUN QUERY
    $result = mysqli_query($mysqli, $sql);
      /**
       * TEST FOR QUERY SUCCESS HERE, POSSIBLY TRIGGER_ERROR()
       */
      // START THE SELECT CONTROL
    $out = '<select name="sede" class="form-control selectpicker" data-live-search="true" id="sede">' . PHP_EOL;
      // THE CURRENT STATE IS KEPT HERE
    $old = '?';
      // THE INITIAL OPTGROUP STATUS IS KEPT HERE
    $grp = FALSE;
      // USE AN ITERATOR TO RETRIEVE THE ROWS OF THE RESULTS SET
    while($row = mysqli_fetch_object($result))
    {
      // IF THIS IS A ROW WITH A NEW STATE?
      if ($row->provincia != $old)
      {
        // IF THERE IS AN EXISTING OPT-GROUP
        if ($grp)
          {
        // TIE OFF THE OLD OPT-GROUP
        $out .= '</optgroup>' . PHP_EOL;
          }
          // ADD THE OPT-GROUP FOR THE NEW STATE
          $out .= '<optgroup label="' . $row->provincia . '">' . PHP_EOL;
          $out .= '<option value="' . $row->sede_ID . '">' . $row->indirizzo . '</option>' . PHP_EOL;
          // CHANGE STATES
          $old = $row->provincia;
          $grp = TRUE;
        }
      // IF THIS IS ANOTHER CITY IN THE SAME STATE
      else
      {
        // JUST ADD THE CITY OPTION
        $out .= '<option value="' . $row->sede_ID . '">' . $row->indirizzo . '</option>' . PHP_EOL;
      }
    }
    // AT THE END OF THE RESULTS SET, TIE OFF THE OPT-GROUP AND THE SELECT CONTROL
    $out .= '</optgroup>' . PHP_EOL;
    $out .= '</select>' . PHP_EOL;
      ?>
      <?php echo $out;  ?>

The problem is when i try to add the code to select the db defined option. The variable for the database option option to be selected is $sede, I tried to make a function that echo selected if $sede is equal (==) to row->sede_ID but it doesn't work. Can anyone please help me with this problem? Thanks


Solution

  • Simple solution, include an extra variable within your tag. If the values don't match you leave this as an empty string, otherwise include the "selected" attribute

    (Within your loop)

    // Show an option for the city
    $out .= "<option value='{$row->sede_ID}'>{$row->indirizzo}</option>" . PHP_EOL;
    

    becomes

    // Decide whether to select the current city as the selected value
    if ( $sede == $row->sede_ID)
    {
        // Select this city
        $selectedText = "selected='selected'";
    }
    else
    {
        // Don't select this city
        $selectedText = "";
    }
    
    // Show an option for the city
    $out .= "<option value='{$row->sede_ID}' $selectedText>{$row->indirizzo}</option>" . PHP_EOL;
    

    Note that for clarity, I've removed your text concatenations and just included the variables within the string: this is usually considered acceptable within PHP: the curly braces {} prevent strange things happening with $object->field variables

    If the $row->sede_id == $sede, it outputs

    <option value='123' selected='selected'>yourtext</option>
    

    Otherwise it outputs

    <option value='123'>yourtext</option>