Zigsaw Consultancy Zigsaw Consultancy - 1 month ago 12
PHP Question

Displaying default value through select tag

I am having trouble passing & displaying default value for select tag. So, I have tried different variants of select and option tag but I am not able to get this right.

I want to fetch different options in form of a drop down menu. I want to display a default value in it. ($categorytemp[$i] in code). On displaying the form


  1. A user can update this choice; or

  2. A user can select the same choice again; or

  3. A user can not change it at all.



Expected result for the above activity should be update, update, default value for $category

Below is the snapshot of my code

<select name="category" value="<?php echo $categorytemp[$i] ?>">



<?php

$sql = "SELECT * FROM education_details";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
$education_category = $row["id"];
$education_name= $row["name"];
?>
<option value='<?php echo $education_category?>'><?php echo $education_name;?></option>
<?php
}
?>
</select>


I tried using the option tag with selected attribute but that is making things more complicated. For example, if I use

<select name="category" value="<?php echo $categorytemp[$i] ?>">
<option selected="selected"><?php echo $categorytemp[$i]; ?> </option>


<?php

$sql = "SELECT * FROM education_details";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result))
{
$education_category = $row["id"];
$education_name= $row["name"];
?>
<option value='<?php echo $education_category?>'><?php echo $education_name;?></option>
<?php
}
?>
</select>


It displays the form as desired but on making no selection, it passes null value in the category. I have gone through questions of similar type asked earlier, but they do not answer my query to my satisfaction

Answer

This did the trick. When no value is selected, pass the default value as value in option

<select name="category" >
                        <option value='<?php echo $categorytemp[$i]?>'><?php echo $categorytemp[$i]; ?> </option>


                            <?php 

                                $sql = "SELECT * FROM education_details";
                                $result = mysqli_query($conn, $sql);
                                    while($row = mysqli_fetch_assoc($result)) 
                                        {
                                            $education_category = $row["id"];
                                            $education_name= $row["name"]; 
                                            ?>
                                            <option value='<?php echo $education_category?>'><?php echo $education_name;?></option>
                                            <?php
                                        }
                            ?>
                            </select> 
Comments