Raphael_b
Raphael_b

Reputation: 1510

sorting element in an object to be displayed using a while loop

I am creating a simple drop-down menu displaying names:

    $sql = "SELECT id, 
                name
            FROM team 
            WHERE 1";
$stmt = $mysqli->prepare($sql);

if ($stmt) {
    $stmt->execute();    
    $stmt->store_result();

    $stmt->bind_result($id, $name);
    while ($stmt->fetch()) {
            echo '<option value=\"$id\">'.utf8_encode($name).'</option>';
    }       
} else {
    header('Location: ../../error.php?err=the database is corrupted');
}

I want to sort the option by alphabetic order. I am not sure which function should I use to sort the object before the loop. Any ideas?

Upvotes: 0

Views: 43

Answers (4)

Pupil
Pupil

Reputation: 23948

$sql = "SELECT `id`, `name` FROM team 
WHERE 1 ORDER BY name";

Default order of Database is ASC, so it works even if you do not write ASC.

Upvotes: 2

Use ORDER BY in your query to get names sorted in alphabetical order.

$sql = "SELECT id, name
        FROM team 
        WHERE 1
        ORDER BY name ASC";

Upvotes: 1

Jens
Jens

Reputation: 69440

Do sorting in sql:

$sql = "SELECT id, 
                name
            FROM team 
            WHERE 1 order by name"

Upvotes: 1

tttpapi
tttpapi

Reputation: 887

$sql = "SELECT id, 
                name
            FROM team 
            WHERE 1 ORDER BY name ASC";

Upvotes: 2

Related Questions