简体   繁体   中英

How to fetch value from mysql to dropdown list?

i am newbie to PHP and MySql. I'm working on small project, some part of this project i have to deal with form and get value back to the field when i need to edit the text. Here's is what i meant

//dropdown list in Create 
<select name="color">
   while($row = $stmt->fetch(PDO::FETCH_ASSOC)) 
                    {
                      echo '<option>'.$row['colors'].'</option>';
                    }
 </select>
<input type="submit" name="submitcolor"/>

//dropdown list in Edit
<select name="color" value="???????">

</select>

i have no problem submit the value to MySql. The problem is, how to fetch the value back to dropdown list, so i don't have to click and search the value.

Thank you for your suggestion.

Try this

<//dropdown list in Create 
<select name="color">
<?php
  while($row = $stmt->fetch(PDO::FETCH_ASSOC)) 
   {
     echo '<option     value="'.$row['colors'].'">'.$row['colors'].'</option>';
   }
 ?>
</select>

  <input type="submit" name="submitcolor"/>

 //dropdown list in Edit
  <select name="color">

<?php
$color = 'some value you fetched from database';
  while($row = $stmt->fetch(PDO::FETCH_ASSOC)) 
   {
     $selected = '';
     if($color == $row['colors']) {
       $selected = 'selected';
     }
     echo '<option value="'.$row['colors'].'" '.$selected.'>'.$row['colors'].'</option>';
   }
 ?>
  </select>

You need to have a value in 'option' tag. And on editing, compare the exisiting 'color' value with the edit selectbox value

this is how you can fill a drop down with mysql results

   <select name="name">                     
        <?php
            $count = count($name);
            for ($i = 0; $i < $count; $i++){    
                    "<option $type[$i]['name'] </option>';
                }
        ?>
    </select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM