nikoh
nikoh

Reputation: 101

Populate dropdown from database and set default value

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!

Upvotes: 1

Views: 2006

Answers (3)

Himanshu Upadhyay
Himanshu Upadhyay

Reputation: 6565

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>";
    
?>

Upvotes: 1

nandal
nandal

Reputation: 2634

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>";

?>

Upvotes: 0

Sandra
Sandra

Reputation: 418

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>";

?>

Upvotes: 0

Related Questions