Reputation: 1510
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
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
Reputation: 1316
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
Reputation: 69440
Do sorting in sql:
$sql = "SELECT id,
name
FROM team
WHERE 1 order by name"
Upvotes: 1