howthegodschill
howthegodschill

Reputation: 95

Order a PHP Dropdown Menu by ID as Opposed to Alphabetical Order

I created a dropdown menu using PHP, which refers to a database for the items. The issue I'm having is that the list is in alphabetical order, and I would like it to be in order by the ID. In this case 'pf_id'.

<?php
    $sql = "SELECT pf_id, primary_function FROM primary_function;";
    $result = mysqli_query($conn, $sql);

    echo "<html>";
    echo "<body>";
    echo "<select name='primary_function' id = 'primary_function'>";

    while ($row = mysqli_fetch_assoc($result)) {
                  unset($id, $name);
                  $id = $row['pf_id'];
                  $name = $row['primary_function'];
                  echo '<option value="'.$name.'"> #'.$id.' '.$name.' </option>';

                }

    echo "</select>";
    echo "</body>";
    echo "</html>";
    ?>

Upvotes: 0

Views: 80

Answers (1)

Martin
Martin

Reputation: 16433

This is as simple as changing the order of the results in the query you are using:

$sql = "SELECT pf_id, primary_function FROM primary_function ORDER BY pf_id;";

Note I added ORDER BY pf_id. This will change the order of your results to be on ascending ID.

Upvotes: 2

Related Questions