douping4436
douping4436
2014-11-26 09:22

使用while循环显示对象中的元素

已采纳

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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • dsdsm2016 dsdsm2016 7年前
    $sql = "SELECT id, 
                    name
                FROM team 
                WHERE 1 ORDER BY name ASC";
    
    点赞 评论 复制链接分享
  • dongyinglan8707 dongyinglan8707 7年前

    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";
    
    点赞 评论 复制链接分享
  • doulong2782 doulong2782 7年前

    Do sorting in sql:

    $sql = "SELECT id, 
                    name
                FROM team 
                WHERE 1 order by name"
    
    点赞 评论 复制链接分享
  • dtz30833 dtz30833 7年前
    $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.

    点赞 评论 复制链接分享