2016-01-06 3 views
1

После ввода правильного кода сортировка таблицы вообще не отображалась. Пожалуйста, помогите мне. Я включил свой CSS-стиль и PHP-кодирование. Спасибо!Сортировка таблицы с использованием PHP

ниже изображение текущего результата:

capture3

это мой PHP кодирование:

<html> 
    <head> 
     <link rel="stylesheet" href="thead.css"/> 

    <script type="text/javascript" src="scripts/jquery-1.11.1.min.js"></script> 
    <script type="text/javascript" src="scripts/jquery.tablesorter.js"></script> 
    <script type ="text/javascript"> 

     $(document).ready(function() 
      { 
       $("#myTable").tablesorter(); 
      } 
     ); 
    </script> 
</head> 
<body> 

    <?php 

    if ($_SESSION ['role_id'] == 1) { ?> 
    <table border="1" cellpadding="0" cellspacing="0"> 

    <table border='1' width='78%' id='myTable' class='tablesorter'> 
        <thead> 
        <tr class= 'header'> 
         <th> Booking ID </th> 
         <th> Staff ID  </th> 
         <th> Asset ID </th> 
         <th> Start Date </th> 
         <th> End Date  </th> 
         <th>Collection Date </th> 
         <th> Actual Return Date </th> 

        </tr> 
        </thead> 
         <tbody> 
     <?php 
       while ($fetchSelect = mysqli_fetch_assoc($result)) { 
       $id = $fetchSelect['booking_id']; 
       $staffid = $fetchSelect['user_id']; 
       $assetid = $fetchSelect['asset_id']; 
       $startdate = $fetchSelect['start_date']; 
       $duedate = $fetchSelect['due_date']; 
       $collectiondate = $fetchSelect['collection_date']; 
       $returndate = $fetchSelect['return_date']; 
       ?> 

         <tr> 
          <td><?php echo $id; ?></td> 
          <td><?php echo $staffid; ?></td> 
          <td><?php echo $assetid; ?></td> 
          <td><?php echo $startdate; ?></td> 
          <td><?php echo $duedate; ?></td> 
          <td><?php echo $collectiondate; ?></td> 
          <td><?php echo $returndate; ?></td> 


    <?php 
     } ?> 
      </tbody> 
      </table> 
    <?php 
    }else{ 
     exit; 
    } 
    </body> 
    </html> 

Мой стиль CSS:

table.sortable thead { 
     background-color:#eee; 
     color:#666666; 
     font-weight: bold; 
     cursor: default; 
    } 

    table.sortable th:not(.sorttable_sorted):not(.sorttable_sorted_reverse):not(.sorttable_nosort):after { 
     content: " \25B4\25BE" 
    } 
+0

Используйте таблицы данных для отображения таблиц. Он предоставляет множество функций, таких как сортировка разбивки на страницы и т. Д. – noor

+2

почему вы начинаете 2 тега таблицы. просто задал вопрос '

' – synan54

+0

Там две инициализированные таблицы, сохраняйте только один. Кроме того, вы забыли закрыть '' в цикле. – Pupil

ответ

0

Для сортировки я использую это:

В моем заголовке таблицы я просто добавить

<th onclick='sortTable(this)'>[HeaderTextHere]</th>

Javascipt код:

var tableId; 
// Gets the table by its id 
var $ = function(id) { return document.getElementById(id); }, 
    $$ = function(query , base) { 
    return (base||document).querySelectorAll(query); 
    }, 
    table = $(tableId), 
    rows = [], 
    cellClassArray = []; 
//populates the row array and the class array 
function getSortable(columnClicked){ 
    var trows = document.getElementById(tableId).rows , //the unmodified rows 
    rows =[], //the rowdata from start to end '<tr>...</tr>' 
    cells =[], //innerHTML of selected cell 
    cellClassArray =[]; //class names from the cells 

    for(var i = 1; i< trows.length; i++) { 
    //contains the class of the working cell 
    var cellClass = trows[i].cells[0].className; 
    //adding the cell values to the cell array 
    cells.push(trows[i].cells[columnClicked].innerHTML); 
    //if a new cellclass comes up then add it to the cellClassArray 
    //later I should also make an array for rowClass so this script also would work on tables where the class is set rowbased 
    if(cellClassArray.indexOf(cellClass) == -1) 
     cellClassArray.push(cellClass); 
    //going through all the cells and deleting all class data 
    for(z = 0; trows[i].cells.length > z; z++) 
     trows[i].cells[z].className = ''; 
    //adding the working row to the rows array 
    rows.push(trows[i]); 
    } 
    //creating and returning the multidim array, could maybe be improved 
    var rowsAndClassArrays = [rows, cellClassArray, cells]; 
    return rowsAndClassArrays; 
} 

//Deletes and re-inserting the table 
function updateRows(rows, tableId, cellClassArray) { 
    //getting the table element 
    var table = document.getElementById(tableId); 
    //Deleting all rows in the table(except the header) 
    while (table.rows.length > 1) { 
    table.removeChild(table.lastChild); 
    } 

    //z shoud be changed to an int later on, to make it possible to have more than 2 row classes 
    var z = true; 
    //Re-inserting the rows 
    for (var i =0; i< rows.length ;i++){ 
    //Seemed better to put it into a var at time of writing 
    var workRow = rows[i]; 
    //when changing z to int remember to also change this if to a switch 
    //Giving the cells a classname if the had any 
    if(z) { 
     for(q = 0; rows[i].cells.length > q; q++) 
     workRow.cells[q].className = cellClassArray[0]; 
    } 
    else { 
     for(q = 0; rows[i].cells.length > q; q++) 
     workRow.cells[q].className = cellClassArray[1]; 
    } 
    z = !z; 
    //appending the rows to the table 
    table.appendChild(workRow); 
    } 
} 

function sortAlphabetically(el, tableId, columnClicked){ 
    //el i a bool for sort direction 
    el.sort = ! el.sort; 
    //array contaning row clases, rows, and value of the rows 
    var rowsAndClassArray = getSortable(columnClicked), 
    rows = []; 
    //creating multidim array to make sorting easy 
    for(var i = 0; i < rowsAndClassArray[0].length; i++) { 
    rows[i] = [rowsAndClassArray[0][i], rowsAndClassArray[2][i]]; //[0] is the raw row data, [1] is the innerHTML of the selected column 
    } 
    //Sorting the rows 
    rows.sort(
    function(a, b) { 
     if (a[1] === b[1]) { 
     return 0; 
     } 
     else { 
      return (el.sort) ? ((a[1] < b[1]) ? -1 : 1) : ((a[1] > b[1]) ? -1 : 1); 
     } 
    } 
); 
    var cleanRows = []; // after sorting we dont need the column values anymore 
    for(var i = 0; i < rows.length; i++) { 
    cleanRows.push(rows[i][0]); 
    } 
    cellClassArray = rowsAndClassArray[1]; 
    //updateRows is deleting all rows and inserting rows in the new order 
    updateRows(cleanRows, tableId, cellClassArray); 
} 

function sortTable(th) { 
    var columnNumber = th.parentNode.parentNode.parentNode.rows[0].cells.length; 
    //Debugging code saved for latter use 
    //console.log(th.parentNode.parentNode.parentNode.rows[0].cells.length); 
    //Caluculates what colum that have been clicked 
    var columnClicked; 
    for(i = 0; i < columnNumber; i++) { 
     if(th == th.parentNode.parentNode.parentNode.rows[0].cells[i]) { 
     columnClicked = i; 
     break; 
     } 
    } 
    //geting the tabel id 
    tableId = th.parentNode.parentNode.parentNode.id; 
    //sorting rows based on the clicked column and updates the table on the page 
    sortAlphabetically(th, tableId, columnClicked); 
} 

Это не является совершенным, и есть некоторые недостатки, но надеюсь, что это может помочь вам двигаться вперед ,

+0

tablesorter - плагин, почему вы хотите разработать собственный код здесь – Sundar

+0

Я не могу вспомнить, почему, но tablesorter дал мне некоторые проблемы/не играл хорошо, когда я играя с сортировкой, и поэтому я сделал собственный код. –

+1

Большое вам спасибо (: Я очень ценю вашу помощь, мой код уже может работать! Отличный день (: – katlurvechoc

0

В некоторых случаях может привести к ошибке

  1. Вы не закрыли закрывающий тег PHP

    <?php }else{ exit; } ?> // '?>' is missed </body> </html>

  2. $ _SESSION [ 'ROLE_ID'] не содержит 1 (может быть).

  3. Если оба указанных выше случаях не SOLN попробовать пример я попытался link

0

Если вы хотите, чтобы отсортировать таблицу с помощью PHP только добавить заказ ACS или DESC в запросе в конце запроса , Он покажет сортировку по вашему желанию.

не нужно сортировать таблицу ... сосредоточиться только на урском запросе.

e. г. выберите * из заказа ученика по меткам desc;

он будет показывать самую высокую отметку первым в сортировке записей.

Это нормально для вас .. или вы хотите сортировать таблицу сорта.

Смежные вопросы