2016-07-10 73 views
1

我有一段課程可以用mysql建立一個php站點。
我需要能夠根據它的列對數據表進行排序。數據是使用PDO從mysql數據庫中檢索的。然後,我只是在循環顯示每行數據時回顯一張表格PHP/MYSQL對mysql數據的echo表進行排序

任何有關如何按列對數據進行排序的想法?最好我希望能夠通過點擊表頭來排序數據(升序)。但我對思想開放。

下面的代碼: PHP:

function displayBooks($data){ 
    echo "<table id= \"allBooks\">"; 
    echo "<th>Book ID</th><th>Title</th><th>Description</th><th>In Stock</th><th>Price</th><th>Cateogry</th>"; 
    #foreach($data as $row) 
    { 
     echo "<tr>"; 
     echo "<td>".$row['bookID']."</td>"; 
     echo "<td>".$row['title']."</td>"; 
     echo "<td>".$row['description']."</td>"; 
     echo "<td>".$row['quantity']."</td>"; 
     echo "<td>£".$row['price']."</td>"; 
     echo "<td>".$row['name']."</td>"; 
     echo "</tr>"; 
    } 
    echo "</table>"; 

....

//Retrieve all books 
    $all_books_query = "SELECT b.bookID,b.title,b.description,b.quantity,b.price,c.name FROM Books b 
    INNER JOIN Book_Category bc ON bc.bookID = b.bookID 
    INNER JOIN Category c ON c.catID = bc.catID 
    GROUP BY b.bookID;"; 
    $rows = $db->query($all_books_query)->fetchAll(); 

我已經在頁面的其餘部分得到了一大堆更多的PHP。不知道我還需要包括什麼來更好地理解問題,但任何想法都會有所幫助。

回答

1

設置一個機制將用戶的排序需求發送回服務器(query param?post?),並使用這些需求在MySQL查詢中設置ORDER BY子句。

1

這裏有一個簡單,non_robust實施

你必須做出一些積極的聯繫,使用參數,就像這樣:

function displayBooks($data){ 
    echo "<table id= \"allBooks\">"; 
    echo "<th><a href='index.php?col=1&order_by=1'>Book ID ASC</a>|<a href='index.php?col=1&order_by=2'>Book ID DESC</a></th><th><a href='index.php?col=2&order_by=1'>Title ASC</a>|<a href='index.php?col=2&order_by=2'>Title ID DESC</a></th>"; 
#foreach($data as $row) 
{ 
    echo "<tr>"; 
    echo "<td>".$row['bookID']."</td>"; 
    echo "<td>".$row['title']."</td>"; 
    echo "</tr>"; 
} 
echo "</table>"; 

和腳本的第二poart

//Retrieve all books 

$order_by = 'ASC'; 
switch ((int)$_GET['order_by']) { 
case 1: 
    $order_by = 'ASC'; 
break; 
case 2: 
    $order_by = 'DESC'; 
break; 
} 


$col= "bookID"; 
switch ((int)$_GET['col']) { 
case 1: 
    $col = 'bookID'; 
break; 
case 2: 
    $col = 'title'; 
break; 
} 


$all_books_query = "SELECT b.bookID,b.title,b.description,b.quantity,b.price,c.name FROM Books b 
INNER JOIN Book_Category bc ON bc.bookID = b.bookID 
INNER JOIN Category c ON c.catID = bc.catID 
GROUP BY b.bookID 
ORDER BY $col $order_by"; 

$rows = $db->query($all_books_query)->fetchAll();