RCode
RCode

Reputation: 379

How to set a default selected option in PHP for a dropdown menu based on a specific condition?

I have a PHP code that generates a dropdown menu from a MySQL database. The dropdown menu is populated with options retrieved from the "inventory" table. I want to set a default selected option based on a specific condition. For example, if the $_GET['in_id'] is set, I want the corresponding option with that In_id to be selected by default when the dropdown is rendered.

Here is the PHP code I'm using to generate the dropdown:

$sql = "SELECT * FROM `inventory`";
$query = mysql_query($sql);
while ($fetch = mysql_fetch_array($query)){
    echo '<option value="'.$fetch['In_id'].'">'.$fetch['In_name'].'</option>';
}

if (isset($_GET['in_id'])){
    $in_id = $_GET['in_id'];
    $sql_in = "SELECT * FROM `inventory` WHERE In_id='$in_id'";
    $query_in = mysql_query($sql_in);
    $fetch_in = mysql_fetch_array($query_in);
}

How can I modify this code to set a default selected option based on the $_GET['in_id'] value?

Upvotes: 0

Views: 44

Answers (1)

sandip patil
sandip patil

Reputation: 658

Try to change your while loop same as below:

 while ($fetch = mysql_fetch_array($query)){
  $in_id = $_GET['in_id'];
  $sel = '';
  if($in_id == $fetch['In_id']){
        $sel = 'selected="selected"';
  }
  echo '<option value="'.$fetch['In_id'].'" '.$sel.'>'.$fetch['In_name'].';}

Upvotes: 1

Related Questions