Search code examples
phphtmlmysqlfetch

How to fetch values to select/option tags from MySQL


I have to fetch values to html option tag with PHP, but instead of fetching names in options I am fetching them in new select tag

enter image description here

Instead the names have to be part of the options in select tag

Here is the fetch:

 <?php  
    $query = $conn->query("SELECT * FROM `agents`") or die(mysqli_error());
    while($fetch = $query->fetch_array()){
    ?>
   <select class="form-select" aria-label="Default select example">
   <option selected>Agent</option>
   <option ><?php echo $fetch['firstName']?><?php echo $fetch['lastName']?></option>

    </select>
      <?php
        }
    ?>

Solution

  • You need to do next:

    <select class="form-select" aria-label="Default select example">
        <option value="" disabled selected>Agent</option>
        <?php  
            $query = $conn->query("SELECT * FROM `agents`");
            if ($query) {
                while($fetch = $query->fetch_array()) {
                    echo "<option>" . $fetch['firstName'] . " " .$fetch['lastName'] . "</option>";
                }
            }
        ?>
    </select>