Skip to content
Advertisement

Why is the first entry of an HTML dropdown not present in a PHP array

I have inserted a portion of code that includes a dropdown that retrieves a list through PHP SELECT etc. When it retrieves the entries (there are about 3000) in the dropdown, it always excludes the first entry. If I then select an entry, the return result in the form is the previous entry, e.g., if I select entry 10 in the dropdown through a SUBMIT button, the returned result is entry 9. I assume it is associated to the first entry not being present.

<div class="container">
    <table class="table table-bordered">
    <thead>
        <tr>
            <th>Collection Town</th>
        </tr>
    </thead>
        <tr>
        <td>
            <form>
                <div class="form-group">
                    <select class="form-control" id="colltown" 
name="colltown">
                <?php {$sql = "SELECT * FROM `town_info`";
                 $sth = $pdo->prepare($sql);
                 $sth->execute();

                 foreach ($sth->fetchAll(PDO::FETCH_ASSOC) as $row1) {
echo $row1['id'], $row1['place_name'];  ?>

<option value="<?php echo $row1['id'], $row1['place_name'];?>">
                  <?php }}?>
        </td>

Advertisement

Answer

Clean up your code and order by id ascending to guarantee getting the right order. also only call fetchAll once initally.

<div class="container">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>Collection Town</th>
      </tr>
    </thead>
    <tr>
      <td>
        <form>
          <div class="form-group">
            <select class="form-control" id="colltown" name="colltown">
              <?php
                $sql = "SELECT * FROM `town_info` ORDER BY id ASC";
                $sth = $pdo->prepare($sql);
                $sth->execute();

                $rows = $sth->fetchAll(PDO::FETCH_ASSOC);
                foreach ($rows as $row) {
                  echo "<option value='$row[id]'>$row[place_name]</option>";
                }
              ?>
            </select>
          </div>
        </form>
      </td>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement