I have a MySQL table with less than a thousand rows and it's fetched by a PHP script. I would like to be able to sort the tbody
by ASC or DESC order when clicking a link and still be able to use the search bar like in the . 的一样使用搜索栏。 However when I try to incorporate the coding in my PHP generated table, my search bar doesn't filter. I must be doing something wrong.
Here's my PHP script:
$result = mysql_query("SELECT * FROM table_name");
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row['fruits']."</td>";
echo "<td>".$row['colors']."</td>";
echo "</tr>";
}
mysql_close();
If possible I'd like to have some hint, snippet or even examples would be great!
Thanks
PHP Solutions :
<?php
$sort_name = "id";
$sort_type = "asc";
if($_GET['sort'] == "fruits")
$sort_name = "fruits_column_name";
else if($_GET['sort'] == "colors")
$sort_name = "colors_column_name";
if($_GET['sort_type'] == "desc")
$sort_type = "desc";
$sql = "SELECT * from mytable where some conditions ORDERBY " . $sort_name . " " . $sort_type;
//run your query;
//later in ur HTML
<tr>
<th><a href="?sort=fruits&sort_type=<?= ($sort_name=='fruits' && $sort_type=='asc')?'desc':'asc' ?>">Fruits</a></th>
<th><a href="?sort=colors&sort_type=<?= ($sort_name=='colors' && $sort_type=='asc')?'desc':'asc' ?>">Colors</a></th>
</tr>
JQuery Solution:
Javascript Library Solution:
use this library https://datatables.net/ very handy and it will gives you everything that you are looking for.
I tryed a little around with both JSFiddle versions and found a working Solution for the Search and Sort, it will also Sort the Search results. Only downside is that the Sort will sort Uppercase bevor Lowercase.
ABC ... Z abc ... z
var $rows = $('#table tbody tr');
$('#search').keyup(function () {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function () {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
function compare(a,b) {
var val1= $(a).find('td').text();
var val2= $(b).find('td').text();
if (val1 < val2)
return -1;
if (val1 > val2)
return 1;
return 0;
}
$('#sort').click(function(){
$('#table').html($('#table tr').sort(compare));
});
Greetings from Germany
KS_HTK
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.