I want to filter the table that I created using PHP in my code. What I want is a dropdown filter that will filter the contents of the table according to the option you select. This is an image of my table and the dropdown that I want to use.
I don't have any idea on doing that since most of the things I researched was only for html. This is my code for the dropdown and the table.
<select id="mylist" class="dropdown-filter">
<option>Any</option>
<option>Regular</option>
<option>Dealer</option>
<option>Refill</option>
</select>
<table class="table datatable text-center" id="transaction-table">
<thead>
<tr>
<th class="text-center">Customer</th>
<th class="text-center" style="pointer-events: none;">Transaction </th>
<th class="text-center">Time</th>
<th class="text-center">Item</th>
<th class="text-center">Quantity</th>
<th class="text-center">Total</th>
<th class="text-center">Returned</th>
<th class="text-center">Damaged</th>
<th class="text-center" style="pointer-events: none;">Action</th>
</tr>
</thead>
<tbody>
<?php
$result = mysqli_query($connections, "SELECT * FROM transac_tbl ORDER BY transac_time DESC");
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$TransactionID = $row['transac_id'];
$Customer = $row['customer'];
$Transaction = $row['transac_type'];
$Time = $row['transac_time'];
$Item = $row['item'];
$Quantity = $row['quantity'];
$TotalPrice = $row['total_price'];
$Returns = $row['gal_return'];
$Damaged = $row['damaged'];
$Status = $row['status'];
if ($Transaction == 0) {
$Transaction1 = "Dealer";
} elseif ($Transaction == 1) {
$Transaction1 = "Regular";
} else {
$Transaction1 = "Refill";
}
if ($Item == 0) {
$Item1 = "Slim";
} else {
$Item1 = "Round";
}
echo '<tr>
<td>'.$Customer.'</td>
<td>'.$Transaction1.'</td>
<td>'.date_format(new DateTime($Time), 'F d, Y | h:i A').'</td>
<td>'.$Item1.'</td>
<td>'.$Quantity.'</td>
<td>'.$TotalPrice.'</td>
<td>'.$Returns.'</td>';
if ($Damaged != 0) {
echo '<td><span class="badge bg-danger">'.$Damaged.'</span></td>';
} else {
echo '<td>None</td>';
}
if ($Status == 0) {
echo '<td><button class="btn btn-dark" type="button" data-bs-toggle="modal" data-bs-target="#verticalycentered" style="margin: 3px; font-size: 13px; padding: 3px 5px; min-width: 50px;">Void</button></td>;
} else {
echo '<td><span class="badge bg-success">Voided</span></td>';
}
}
}
?>
P.S Sorry for the long code, I'm still studying and uses many inefficient methods
It depends on how you want to implement the feature, front-end or back-end.
You have to decide that based on factors like your data, implementation, load speed consideration, filter speed consideration, pagination etc.
1. Front End:
You can use libraries like Datatables and create custom filters according to your need. This will filter your table based on data available on page.
Note: In case you have backend based pagination, you have to opt for backend filtering to get data beyond the current page.
2. Backend:
You can use ajax/forms etc. to communicate with backend (PHP in this case) and get filtered data.
I have issues with my table, I cannot use Javascript (which I know would be easier). I can only use HTML, PHP and CSS. This is my code that I currently have. The issues I need to resolve are the following:
I am able to add rows, delete and I am so also able to edit them by using the "contenteditable", however my issue is that every time I add a row or remove one, it refreshes the whole page. How can I fix this issue?
Also if there is a way to have an edit button instead of my conteneditable method.
Here is my code:
input {
display: block; /* makes one <input> per line */
width: 150px;
}
<?php
if( isset( $_REQUEST["btnadd"]) == "ADD") {
// add 1 to the row counter
if (isset($_REQUEST['count'])) $count = $_REQUEST['count'] + 1;
// set value for first load
else $count = 1;
}
if( isset( $_REQUEST["btnremove"]) == "REMOVE") {
// decrement the row counter
$count = $_REQUEST['count'] - 1;
// set minimum row number
if ($count < 1) $count = 1;
}
?>
<form name="form1">
<table class="table table-bordered table-striped table-hover text-center" align='center'>
<tr>
<th align="center">Name</th>
<th>Start </th>
<th>Size</th>
<th>First Condition</th>
<th>Second Conditon</th>
<th><input type="submit" name="btnadd" id="btnadd" value="ADD" align='center'></th>
</tr>
<?php
// print $count rows
for ($i=1; $i<=$count; $i++) {
echo ' <tr>
<td contenteditable="true"></td>
<td contenteditable="true"></td>
<td contenteditable="true"></td>
<td contenteditable="true"></td>
<td contenteditable="true"></td>
<td> <input type="submit" name="btnremove" id="btnremove" value="REMOVE"></td>
</tr>
';
}
?>
</table>
<input type="hidden" name="count" value="<?php echo $count; ?>">
</form>
every time I add a row or remove one, it refreshes the whole page. How can I fix this issue?
Without Javascript you can't.
if there is a way to have an edit button instead of my conteneditable method
It's rather hard to suggest what your code should be since you don't ofer a description of what the code is intended to do, other than the code which doesn't do what you want. I think you mean something like:
<?php
$width=5;
$data=isset($_REQUEST['data']) ? $_REQUEST['data'] : array();
$count=count($data);
if (isset($_REQUEST['delete'])) {
foreach ($_REQUEST['delete'] as $i) {
unset($data[$i]);
}
}
$data=array_values($data);
if( isset( $_REQUEST["btnadd"]) == "ADD") {
// add 1 to the row counter
$data[]=array();
}
...
foreach ($data as $i=>$row) {
print "<tr>\n";
for ($x=0; $x<$width; $x++) {
#print "<td><input type='text' name='data[$i][$x]'></td>\n";
}
print "<td><input type='checkbox' name='delete[]' value='$i'>";
print "</tr>\n";
}
print "<tr>
<td colspan='$width'>
<input type="submit" name="btnadd" id="btnadd" value="Add">
</td>
</tr>\n";
I have a niggling error that no one seems to be able to fix but I'm sure it is very simple and possibly CSS related.
I wish for the first column (that is the usernames) to be frozen/fixed in order for the user to scroll through the other columns (the tests, of which there are many).
This now works, but the positioning of the username is out of synch with the rest of the table.
It looks like this:
and it should look like:
PHP and HTML code:
<?php }elseif(isset($_POST['quiz']) && $_POST['quiz'] == "non" && $err == ""){ ?>
<div class="col-sm-12">
<div class="table-responsive">
<table class="table table-bordered table-striped table-condensed" id="table">
<thead>
<tr>
<td width="3%"></td>
<?php
$all_quizes = mysqli_query($con,"SELECT * FROM quizes ORDER BY FIELD(quiz_level, 'Beginner','Intermediate','Advanced'),quiz_name ASC");
$quizes = array();
while($my_rows = mysqli_fetch_array($all_quizes)){
array_push($quizes,$my_rows);
}
foreach($all_quizes as $record){
?>
<th width="30%"><?php echo $record['quiz_name']; ?></th>
<?php } ?>
</tr>
</thead>
<tbody>
<?php foreach(#$result as $record){?>
<tr>
<td class="headcol"><?php echo $record["username"];?></td>
<?php
$counter=0;
echo " ";
while(mysqli_num_rows($all_quizes) > $counter){
$current_td = mysqli_query($con,"SELECT * FROM quiz_takers WHERE username='".$record["username"]."' AND quiz_id=".$quizes[$counter][0]." ORDER BY marks DESC");
$td = mysqli_fetch_array($current_td);
if($td['percentage'] == null){
echo "<td> ?</td>";
}else{
if(intval($td["percentage"]) >= 0 && intval($td["percentage"]) <= 30){
$color = 'red';
}elseif(intval($td["percentage"]) > 30 && intval($td["percentage"]) <= 70){
$color = '#ffbf00';
}elseif(intval($td["percentage"]) <= 30){
}else{
$color = 'green';
}
echo "<td style='color:".$color."'>".round($td["percentage"],2)."%</td>";
}
$counter++;
}
/*foreach($current_td as $td){
echo $counter." ".$td['username'] . " - ".$quizes[$counter]['3']."<br>";
if($quizes[$counter]['0'] == $td['quiz_id']){
?>
<td><?php echo $td["percentage"];?></td>
<?php } $counter++;}*/ ?>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
The current css is:
<style>
.headcol {
position:absolute;
height:100px;
width: 5em;
left: -10;
overflow-x: scroll;
margin-left: 5em;
padding: 0;
top: 2;
border-top-width: -2px;
/*only relevant for first row*/
margin-top: -90px;
/*compensate for top border*/
}
</style>
Could someone please suggest a solution or fix?
I think the issue coming from the first column of the first heading row, which you defined the width of 3%. This width should equal to the width of .headcol
Something like this
<thead>
<tr>
<td width="5em"></td> //equal to the width of .headcol
Besides, you may need to adjust your CSS of .headcol so it can be aligned better, maybe put left: 0;
I want a zebra striped table.
The data is extracted from the database and every instance creates a new table.
I want the zebra-striped on the <table> level. this would mean that every other <table> element gets a different color.
I tried to add a class to my <table class="oddeven"> but this still does the changing on every tr.
Here is the code I use it on:
<?php
global $wpdb;
$sql = "SELECT * FROM $wpdb->postmeta WHERE meta_key = 'group' AND meta_value='$group'";
$results = $wpdb->get_results($sql) or die(mysql_error());
echo'<table cellpadding="0" cellspacing="0" border="0" width="100%">';
foreach( $results as $result )
{
$post_id = $result->post_id;
$company_name = get_post_meta($post_id, 'company_name', true);
$address = get_post_meta($post_id, 'address', true);
$postal_code = get_post_meta($post_id, 'postal_code', true);
$city = get_post_meta($post_id, 'city', true);
$phone = get_post_meta($post_id, 'phone', true);
echo '
<tr>
<td>
<table cellpadding="0" cellspacing="0" border="0" width="100%" class="oddeven">
<tr>
<td width="75%">
<strong>'.$company_name.'</strong>
</td>
<td rowspan="4"><img class="table_image" src="'.get_bloginfo('template_directory').'/images/arrow.png"></td>
</tr>
<tr>
<td>
'.$address.'
</td>
</tr>
<tr>
<td>
'.$postal_code.' '.$city.'
</td>
</tr>
<tr>
<td>
'.$phone.'
</td>
</tr>
</table>
</td>
</tr>';
}
echo '</table>';
?>
This is the styling:
(while typing this I realise that this is on tr:level)
.oddeven tr:nth-child(odd){
background: #ffffff;
}
.oddeven tr:nth-child(even){
background: #000000;
}
I hope I make myself clear
If you change your foreach loop to a for loop like this:
for($i = 0; $i < count($results); $i++) {
$result = $results[$i];
...
Then you can figure out if the current row is even or odd by testing if $i % 2 == 0. If that evaluates to true, then add an 'even' class; else add an 'odd' class.
If you do not want to propagate the change to child tables, you can also enforce the same color on the children :
.top tr:nth-child(odd) {
background-color: red;
}
.top tr:nth-child(odd) tr {
background-color: red;
}
.top tr:nth-child(even) {
background-color: yellow;
}
.top tr:nth-child(even) tr {
background-color: yellow;
}
I assume that's what your want since you already have stripped rows on your nested tables
Or maybe I got it wrong, you might have to explain what the <table> level is, since your have nested tables.
I know it's such a basic thing, but a Google search hasn't shown me how to re-sort the rows after clicking the th links.
I've got this:
<table border="1">
<tr>
<th>Type:</th>
<th>Description:</th>
<th>Recorded Date:</th>
<th>Added Date:</th>
</tr>
<?php
while($row = mysql_fetch_array($result)){
?>
<tr>
<td><?php echo $row['type'] ?></td>
<td><?php echo $row['description'] ?></td>
<td><?php echo $row['recorded_date'] ?></td>
<td><?php echo $row['added_date'] ?></td>
</tr>
<br />
<?php
}
mysql_close();
?>
</table>
I need to be able to click type and sort alphabetically, and click on either Recorded Date or Added Date and sort by date. I see that I need to have the MySQL queries do this, but do I set them up as conditionals with a href tags?
The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.
The HTML would look like this:
<th>Type:</th>
<th>Description:</th>
<th>Recorded Date:</th>
<th>Added Date:</th>
And in the php code, do something like this:
<?php
$sql = "SELECT * FROM MyTable";
if ($_GET['sort'] == 'type')
{
$sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
$sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
$sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
$sql .= " ORDER BY DateAdded";
}
$>
Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;
That's actually pretty easy, here's a possible approach:
<table>
<tr>
<th>
Type:
</th>
<th>
Description:
</th>
<th>
Recorded Date:
</th>
<th>
Added Date:
</th>
</tr>
</table>
<?php
$orderBy = array('type', 'description', 'recorded_date', 'added_date');
$order = 'type';
if (isset($_GET['orderBy']) && in_array($_GET['orderBy'], $orderBy)) {
$order = $_GET['orderBy'];
}
$query = 'SELECT * FROM aTable ORDER BY '.$order;
// retrieve and show the data :)
?>
That'll do the trick! :)
A SIMPLE TABLE SORT PHP CODE:
(the simple table for several values processing and sorting, using this sortable.js script )
<html><head>
<script src="sorttable.js"></script>
<style>
tbody tr td {color:green;border-right:1px solid;width:200px;}
</style>
</head><body>
<?php
$First = array('a', 'b', 'c', 'd');
$Second = array('1', '2', '3', '4');
if (!empty($_POST['myFirstvalues']))
{ $First = explode("\r\n",$_POST['myFirstvalues']); $Second = explode("\r\n",$_POST['mySecondvalues']);}
?>
</br>Hi User. PUT your values</br></br>
<form action="" method="POST">
projectX</br>
<textarea cols="20" rows="20" name="myFirstvalues" style="width:200px;background:url(untitled.PNG);position:relative;top:19px;Float:left;">
<?php foreach($First as $vv) {echo $vv."\r\n";}?>
</textarea>
The due amount</br>
<textarea cols="20" rows="20" name="mySecondvalues" style="width:200px;background:url(untitled.PNG);Float:left;">
<?php foreach($Second as $vv) {echo $vv."\r\n";}?>
</textarea>
<input type="submit">
</form>
<table class="sortable" style="padding:100px 0 0 300px;">
<thead style="background-color:#999999; color:red; font-weight: bold; cursor: default; position:relative;">
<tr><th>ProjectX</th><th>Due amount</th></tr>
</thead>
<tbody>
<?php
foreach($First as $indx => $value) {
echo '<tr><td>'.$First[$indx].'</td><td>'.$Second[$indx].'</td></tr>';
}
?>
</tbody>
<tfoot><tr><td>TOTAL = <b>111111111</b></td><td>Still to spend = <b>5555555</b></td></tr></tfoot></br></br>
</table>
</body>
</html>
source: php sortable table
//this is a php file
<html>
<head>
<style>
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
table
{
width:50%;
height:50%;
}
table,th,td
{
border:1px solid black;
}
th,td
{
text-align:center;
background-color:yellow;
}
th
{
background-color:green;
color:white;
}
</style>
<script type="text/javascript">
function working(str)
{
if (str=="")
{
document.getElementById("tump").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("tump").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsort.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body bgcolor="pink">
<form method="post">
<select name="sortitems" onchange="working(this.value)">
<option value="">Select</option>
<option value="Id">Id</option>
<option value="Name">Name</option>
<option value="Email">Email</option>
<option value="Password">Password</option>
</select>
<?php
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("test1",$connect);
$sql=mysql_query("select * from mine");
echo "<center><br><br><br><br><table id='tump' border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>";
echo "<tr>";
while ($row=mysql_fetch_array($sql))
{?>
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
}
echo "</table></center>";?>
</form>
<br>
<div id="tump"></div>
</body>
</html>
------------------------------------------------------------------------
that is another php file
<html>
<body bgcolor="pink">
<head>
<style>
a:link {color:green;}
a:visited {color:purple;}
A:active {color: red;}
A:hover {color: red;}
table
{
width:50%;
height:50%;
}
table,th,td
{
border:1px solid black;
}
th,td
{
text-align:center;
background-color:yellow;
}
th
{
background-color:green;
color:white;
}
</style>
</head>
<?php
$q=$_GET['q'];
$connect=mysql_connect("localhost","root","");
$db=mysql_select_db("test1",$connect);
$sql=mysql_query("select * from mine order by $q");
echo "<table id='tump' border='1'>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Password</th>
</tr>";
echo "<tr>";
while ($row=mysql_fetch_array($sql))
{?>
<td><?php echo "$row[Id]";?></td>
<td><?php echo "$row[Name]";?></td>
<td><?php echo "$row[Email]";?></td>
<td><?php echo "$row[Password]";?></td>
<?php echo "</tr>";
}
echo "</table>";?>
</body>
</html>
that will sort the table using ajax
This is the most simple solution that use:
// Use this as first line upon load of page
$sort = $_GET['s'];
// Then simply sort according to that variable
$sql="SELECT * FROM tracks ORDER BY $sort";
echo '<tr>';
echo '<td>Title<td>';
echo '<td>Album<td>';
echo '<td>Artist<td>';
echo '<td>Count<td>';
echo '</tr>';
It depends on nature of your data. The answer varies based on its size and data type. I saw a lot of SQL solutions based on ORDER BY. I would like to suggest javascript alternatives.
In all answers, I don't see anyone mentioning pagination problem for your future table. Let's make it easier for you. If your table doesn't have pagination, it's more likely that a javascript solution makes everything neat and clean for you on the client side. If you think this table will explode after you put data in it, you have to think about pagination as well. (you have to go to first page every time when you change the sorting column)
Another aspect is the data type. If you use SQL you have to be careful about the type of your data and what kind of sorting suites for it. For example, if in one of your VARCHAR columns you store integer numbers, the sorting will not take their integer value into account: instead of 1, 2, 11, 22 you will get 1, 11, 2, 22.
You can find jquery plugins or standalone javascript sortable tables on google. It worth mentioning that the <table> in HTML5 has sortable attribute, but apparently it's not implemented yet.