我该如何制作" foreach"按字母顺序列出项目

时间:2016-02-17 19:30:00

标签: php mysql

我希望按字母顺序列出项目(或本例中的游戏标题)。

使用php我从mysql数据库获取游戏,我使用foreach轻松列出所有游戏,但我需要它按字母顺序列出它们。

games.php

<table style="width:100%;" class="hover">
    <th style="width:5%;">A-Z</th>
    <th style="width:70%;">Games</th>
    <th style="width:10%;">Clans</th>
    <th style="width:10%;">Recruiting</th>


    <tr>
        <td></td>
        <td>None Specified</td>
        <td></td>
        <td></td>
    </tr>
<?php 
    $query = " 
        SELECT 
            az,
            games,
            clans,
            recruiting
        FROM games 
    "; 

    try 
    { 
        // These two statements run the query against your database table.
        $stmt = $db->prepare($query); 
        $stmt->execute(); 
    } 
    catch(PDOException $ex) 
    { 
        // Note: On a production website, you should not output $ex->getMessage(). 
        // It may provide an attacker with helpful information about your code.  
        die("Failed to run query: " . $ex->getMessage()); 
    } 

    // Finally, we can retrieve all of the found rows into an array using fetchAll 
    $rows = $stmt->fetchAll(); 
?> 


<?php foreach($rows as $row): ?> 
    <tr>
        <td><?php echo $row['az']; ?></td>
        <td><a href="/games/"><?php echo $row['games']; ?></a></td>
        <td><?php echo $row['clans']; ?></td>
        <td><?php echo $row['recruiting']; ?></td>
    </tr>
<?php endforeach; ?>


<tr>
    <th style="width:5%;">A-Z</th>
    <th style="width:70%;">Games</th>
    <th style="width:10%;">Clans</th>
    <th style="width:10%;">Recruiting</th>  
</tr>
</table>

2 个答案:

答案 0 :(得分:1)

只需在查询中输入ORDER:

$query = " 
    SELECT 
        az,
        games,
        clans,
        recruiting
    FROM `games` 
    ORDER BY games ASC
"; 

答案 1 :(得分:0)

您需要将MySQL更新为

SELECT 
    az,
    games,
    clans,
    recruiting
FROM games 
ORDER BY games ASC