1

Right now I have a working solution for populating an HTML <select>/<option>-dropdown with the content through PHP/MYSQLI from my database: listoption.

The database:

DATABASE NAME: 
# listoption

TABLES:
# ID INT(11) *Primary AI
# listoption_item VARCHAR(255)

Here's the other code (not the mysqli connect but everything afterwards..)

<?php

    $result = $mysqli->query("select * from listoption");

    echo "<select id='list' name='list'>";

      while ($row = $result->fetch_assoc()) {

        $listoption_item = $row['listoption_item'];

        echo '<option value="'.$listoption_item.'">'.$listoption_item.'</option>';

      }

    echo "</select>";

?>

But the problem is now that I want to have one of these options that are populated through that query to be selected. And the option to be selected should be determed by a parameter in the URL, for example: index.php?id=1. So now I need to somehow add a IF/ELSE and a $_GET['id']; into the code to make it identify if the ID from the database is the same as the populated item and then set it to selected.

Any idéas? Thanks!

3 Answers 3

1

You can do that like given below:

<?php

    $result = $mysqli->query("select * from listoption");
    $id = ($_GET['id'])? $_GET['id'] : '';

    echo "<select id='list' name='list'>";

      while ($row = $result->fetch_assoc()) {

        $listoption_item = $row['listoption_item'];
        $sel = ($id == $row['id'])? 'selected="selected"':'';
        
        echo '<option value="'.$listoption_item.'" '.$sel.'>'.$listoption_item.'</option>';  // $sel will deside when to set `selected`
        
      }
    
    echo "</select>";
    
?>
Sign up to request clarification or add additional context in comments.

Comments

0

You can rewrite the code as follows:

<?php
    $id = $_GET['id'];
    $select = "";
    $result = $mysqli->query("select * from listoption");

    echo "<select id='list' name='list'>";

      while ($row = $result->fetch_assoc()) {
        $row_id = $row['ID'];
        if($row_id == $id){
           $select = "selected";
        }
        $listoption_item = $row['listoption_item'];

        echo '<option value="'.$listoption_item.'" selected="'.$select.'">'.$listoption_item.'</option>';

      }

    echo "</select>";

?>

Comments

0

Use the following code:-

<?php

$selectedId = isset($_GET['id'])?$_GET['id']:0;
$result = $mysqli->query("select * from listoption");

echo "<select id='list' name='list'>";

  while ($row = $result->fetch_assoc()) {

    $listoption_item = $row['listoption_item'];

    echo '<option value="'.$listoption_item.' .(($selectedId>0)?:" selected ":"").'">'.$listoption_item.'</option>';

  }

echo "</select>";

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.