Question

[Solved] selected value get from db into dropdown select box option using php mysql error

I need to get selected value from db into select box. please, tell me how to do it. Here is the code.
Note: ‘options’ value depends on the category.

<?php 
  $sql = "select * from mine where username="$user" ";
  $res = mysql_query($sql);
  while($list = mysql_fetch_assoc($res)){
    $category = $list['category'];
    $username = $list['username'];
    $options = $list['options'];
?>

<input type="text" name="category" value="<?php echo '$category' ?>" readonly="readonly" />
<select name="course">
   <option value="0">Please Select Option</option>
   <option value="PHP">PHP</option>
   <option value="ASP">ASP</option>
</select>

<?php 
  }
?>

Solution #1:

I think you are looking for below code changes:

<select name="course">
<option value="0">Please Select Option</option>
<option value="PHP" <?php if($options=="PHP") echo 'selected="selected"'; ?> >PHP</option>
<option value="ASP" <?php if($options=="ASP") echo 'selected="selected"'; ?> >ASP</option>
</select>
Respondent: rakeshjain

Solution #2:

The easiest way I can think of is the following:

<?php

$selection = array('PHP', 'ASP');
echo '<select>
      <option value="0">Please Select Option</option>';

foreach ($selection as $selection) {
    $selected = ($options == $selection) ? "selected" : "";
    echo '<option '.$selected.' value="'.$selection.'">'.$selection.'</option>';
}

echo '</select>';

The code basically places all of your options in an array which are called upon in the foreach loop. The loop checks to see if your $options variable matches the current selection it’s on, if it’s a match then $selected will = selected, if not then it is set as blank. Finally the option tag is returned containing the selection from the array and if that particular selection is equal to your $options variable, it’s set as the selected option.

Respondent: independent.guru

Solution #3:

for example ..and please use mysqli() next time because mysql() is deprecated.

<?php
$select="select * from tbl_assign where id='".$_GET['uid']."'"; 
$q=mysql_query($select) or die($select);
$row=mysql_fetch_array($q);
?>

<select name="sclient" id="sclient" class="reginput"/>
<option value="">Select Client</option>
<?php $s="select * from tbl_new_user where type="client"";
$q=mysql_query($s) or die($s);
while($rw=mysql_fetch_array($q))
{ ?>
<option value="<?php echo $rw['login_name']; ?>"<?php if($row['clientname']==$rw['login_name']) echo 'selected="selected"'; ?>><?php echo $rw['login_name']; ?></option>
<?php } ?>
</select>
Respondent: chirag ode

Solution #4:

Select value from drop down.

<select class="form-control" name="category" id="sel1">
    <?php foreach($data as $key =>$value) { ?>                         
        <option value="<?php echo $data[$key]->name; ?>"<?php if($id_name[0]->p_name==$data[$key]->name) echo 'selected="selected"'; ?>><?php echo $data[$key]->name; ?></option>
    <?php } ?>
</select> 
Respondent: Siddharth Shukla

Solution #5:

THE EASIEST SOLUTION

It will add an extra in your options but your problem will be solved.

<?php 
    if ($editing == Yes) {
        echo "<option value="".$MyValue."" SELECTED>".$MyValue."</option>";
    }
?>
Respondent: K. Raza

Solution #6:

BEST code and simple

<select id="example-getting-started" multiple="multiple" name="category">

    <?php
    $query = "select * from mine";
    $results = mysql_query($query);

    while ($rows = mysql_fetch_assoc(@$results)){ 
    ?>
    <option value="<?php echo $rows['category'];?>"><?php echo $rows['category'];?></option>

    <?php
    } 
    ?>
</select>
Respondent: razvan

Solution #7:

You can also do like this ….

<?php  $countryname = $all_meta_for_user['country']; ?>

<select id="mycountry"  name="country" class="user">

    <?php $myrows = $wpdb->get_results( "SELECT * FROM wp_countries order by country_name" );
    foreach($myrows as $rows){
        if( $countryname == $rows->id ){ 
            echo "<option selected = 'selected' value="".$rows->id."">".$rows->country_name."</option>";
        } else{ 
            echo "<option value="".$rows->id."">".$rows->country_name."</option>";
        }
    }
    ?>
</select>
Respondent: narinder kumar

Solution #8:

Just Add an extra hidden option and print selected value from database

<option value="<?php echo $options;?>" hidden><?php echo $options;?></option>
<option value="PHP">PHP</option>
<option value="ASP">ASP</option>
Respondent: Nasser

Solution #9:

Answer is simple.
when u pass value from dropdown.

Just use as if else.

for eg:

foreach($result as $row) {                      
   $GLOBALS['output'] .='<option value="'.$row["dropdownid"].'"'. 
   ($GLOBALS['passselectedvalueid']==$row["dropwdownid"] ? ' Selected' : '').' 
   >'.$row['valueetc'].'</option>';
}
Respondent: siraj

Solution #10:

<?php 
  $sql = "select * from mine where username="$user" ";
  $res = mysql_query($sql);
  while($list = mysql_fetch_assoc($res)){
    $category = $list['category'];
    $username = $list['username'];
    $options = $list['options'];
?>

<input type="text" name="category" value="<?php echo '$category' ?>" readonly="readonly" />
<select name="course">
<option value="0">Please Select Option</option>
<option value="PHP" <?php echo $options == 'PHP' ? 'selected' : ''; ?> >PHP</option>
<option value="ASP" <?php echo $options == 'ASP' ? 'selected' : ''; ?> >ASP</option>
</select>

<?php 
  }
?>

Solution #11:

USING PDO

<?php
$username = "root";
$password = "";
$db = "db_name";

$dns = "mysql:host=localhost;dbname=$db;charset=utf8mb4";
$conn = new PDO($dns,$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$sql = "select * from mine where username = ? ";

$stmt1 = $conn->prepare($sql);
$stmt1->execute(array($_POST['user']));
$all = $stmt1->fetchAll(); ?>

<div class="controls">
    <select  data-rel="chosen"  name="degree_id" id="selectError">
        <?php 
        foreach($all as $nt) { 
            echo "<option value =$nt[id]>$nt[name]</option>";
        }
        ?>
    </select>
</div>
Respondent: 7ani9

Solution #12:

I’m using eval() PHP function like this:

My PHP code:

$selOps1 = $selOps2 = $selOps3 = '';
eval('$selOps'. $dbRow["DBitem"] . ' = "selected";');

Then in my select box I use it like this:

<select>
   <option <?=$selOps1?> value="1">big</option>
   <option <?=$selOps2?> value="2">Middle</option>
   <option <?=$selOps3?> value="3">Small</option>
</select>
Respondent: cheinan

Solution #13:

This may help you.

?php 
$sql = "select * from mine where username="$user" ";
$res = mysql_query($sql);
while($list = mysql_fetch_assoc($res))
{
$category = $list['category'];
$username = $list['username'];
$options = $list['options'];
?>
<input type="text" name="category" value="<?php echo '$category' ?>" readonly="readonly" />
<select name="course">
<option value="0">Please Select Option</option>
// Assuming $list['options'] is a coma seperated options string 
$arr=explode(",",$list['options']);
<?php foreach ($arr as $value) { ?>
   <option value="<?php echo $value; ?>"><?php echo $value; ?></option>
<?php } >
</select>

<?php 
}
?>
Respondent: Pradeeshnarayan

Solution #14:

okay first I think,
you need to get some data form the database and show it in the select box as option then you need to save that select option value into the database.

  1. first you have to get the values from the database
function showAllData(){
    $connection = mysqli_connect('localhost', 'root', '', 'beva');
    $query = "SELECT * FROM users";
    $result = mysqli_query($connection, $query);

    if(!$result){
        die('Query Failed'. mysqli_error());
    }
    while($row = mysqli_fetch_assoc($result)){
        $id = $row['id'];
        echo $id;
        echo "<option name="$id">$id</option>";
    } 
}
  1. then you have to call this function on the select option
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-b5kHyXgcpbZJO/tY9Ul7kGkf1S0CWuKcCD38l8YkeH8z8QjE0GmW1gYU5S9FOnJ0" crossorigin="anonymous"></script>
</head>
<body>
<div class="container mt-3 mb-5">
    <div class="card">
        <form action="html.php" method="post">
            <input type="text" name="username" placeholder="Enter Username">
            <input type="password" name="password" placeholder="Enter Password">
            <select name="se"> <?php showAllData();?> </select>
            <input type="submit" name="submit">
        </form>
    </div>
</div>
</body>
</html>

in here you just calling that function. make sure that you have put a name <select name="se"> for the select box

  1. then you have to do is save that value in the database
if(isset($_POST['submit'])){
        $connection = mysqli_connect('localhost', 'root', '', 'beva');
        $username = $_POST['username'];
        $password = $_POST['password'];
        $id = $_POST['se'];
        echo $id;

        $query = "UPDATE users SET username="$username", password = '$password' WHERE id = $id ";

        $result = mysqli_query($connection, $query);
        echo $query;
        if(!$result){
            echo $query;
            die("Query Failed" . mysqli_error($connection));
        }  
}
  1. then it will update you record and in here you don’t have to create the list one by one
Respondent: Jeffery White

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy