簡體   English   中英

如何通過單擊標題[PHP / MYSQL]對html表列進行排序

[英]How to sort a html table column by clicking the header [PHP/MYSQL]

我有一個表,該表由mysql數據庫中的數據填充,我需要能夠單擊表的某些列以對它們進行升序和降序排序,如果我可以使用php html或javascript,我不確定如何進行此操作,我將附上一張圖片以顯示我已經擁有的內容,以便更好地了解我正在談論的內容https://imgur.com/a/ypnNxB0

<?php
$connection = mysqli_connect('localhost', 'root', '','nba201819'); //The Blank string is the password


$result = mysqli_query($connection,"SELECT * FROM `teamstats` ORDER BY `teamstats`.`WIN%` DESC");

?>

<table id="teamstats" border ='2'>
  <tr>
    <th></th>
    <th>Code</th>
    <th>Team</th>
    <th>GP</th>
    <th>W</th>
    <th>L</th>
    <th><a href='?sortBy=WIN%'>WIN%</th>
    <th>MIN</th>
    <th><a href='?sortBy=PTS'>PTS</th>
    <th><a href='?sortBy=FGM'>FGM</th>
    <th>FGA</th>
    <th>FG%</th>
    <th><a href='?sortBy=3PM'>3PM</th>
    <th>3P%</th>
    <th><a href='?sortBy=FTM'>FTM</th>
    <th>FTA</th>
    <th>FT%</th>
    <th>OREB</th>
    <th>DREB</th>
    <th><a href='?sortBy=REB'>REB</th>
    <th>AST</th>
</tr>
<?php
    while($row = mysqli_fetch_array($result))
    {

    echo "<tr>";
    echo "<td><img src='logos/".$row['TEAMCODE']."_logo.svg' width =20 height=20></td>" ;
    echo "<td>" . $row['TEAMCODE'] . "</td>";
    echo "<td>" . $row['NAME'] . "</td>";
    echo "<td>" . $row['GP'] . "</td>";
    echo "<td>" . $row['W'] . "</td>";
    echo "<td>" . $row['L'] . "</td>";
    echo "<td>" . $row['WIN%'] . "</td>";
    echo "<td>" . $row['MIN'] . "</td>";
    echo "<td>" . $row['PTS'] . "</td>";
    echo "<td>" . $row['FGM'] . "</td>";
    echo "<td>" . $row['FGA'] . "</td>";
    echo "<td>" . $row['FG%'] . "</td>";
    echo "<td>" . $row['3PM'] . "</td>";
    echo "<td>" . $row['3P%'] . "</td>";
    echo "<td>" . $row['FTM'] . "</td>";
    echo "<td>" . $row['FTA'] . "</td>";
    echo "<td>" . $row['FT%'] . "</td>";
    echo "<td>" . $row['OREB'] . "</td>";
    echo "<td>" . $row['DREB'] . "</td>";
    echo "<td>" . $row['REB'] . "</td>";
    echo "<td>" . $row['AST'] . "</td>";

    echo "</tr>";

    }

    echo "</table>";


?>

有各種js插件可幫助實現數據表排序,例如easyui,datatables等。

如果只想使用提供的簡單代碼來實現它,則必須檢索sortBy變量並將其放入SQL查詢中:

$connection = mysqli_connect('localhost', 'root', '','nba201819'); //The Blank string is the password


if (isset($_GET['sortBy'])) {
    if ($_GET['sortBy'] !== '') {
        $sortBy = str_replace( "`", "``", $_GET['sortBy']);
    } else {
        $sortBy = 'WIN%';
    }
} else {
    $sortBy = 'WIN%';
}

$result = mysqli_query($connection,"SELECT * FROM `teamstats` ORDER BY `teamstats`.`$sortBy` DESC");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM