Filter SQL Data on HTML Table - javascript

I'm trying to find a way to filter my sql data from a mysql database on my html table. The trouble I've had is because it's a dynamic table. Should I be sorting on the html table, and if so, how do I get the result html from the sql query (the entire table), as opposed to the html that's just a single row.
If I need to sort on the SQL query itself, how can I do this without needing to refresh the page every time?
Thanks for any help!
Here's my code for reference:
<?php
$host=""; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name ORDER BY id DESC";
// OREDER BY id DESC is order result by descending
}
$result=mysql_query($sql);
?>
<html>
<head>
<script type="text/javascript" charset="utf-8" src="jquery.js"></script>
</head>
<table id="forum" width="90%" border="0" align="center" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<thead>
<tr>
<th width="6%" align="center" bgcolor="#E6E6E6"><strong>#</strong></td>
<th width="43%" align="center" bgcolor="#E6E6E6"><strong>Topic</strong></td>
<th width="10%" align="center" bgcolor="#E6E6E6"><strong>Author</strong></td>
<th width="15%" align="center" bgcolor="#E6E6E6"><strong>Views</strong></td>
<th width="13%" align="center" bgcolor="#E6E6E6"><strong>Replies</strong></td>
<th width="13%" align="center" bgcolor="#E6E6E6"><strong>Date/Time</strong></td>
</tr>
</thead>
<?php
// Start looping table row
while($rows=mysql_fetch_array($result)){
?>
<tbody>
<tr>
<td bgcolor="#FFFFFF"><? echo $rows['threadtype']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['topic']; ?><BR></td>
<td align="center" bgcolor="#FFFFFF"><? echo $rows['email']; ?></td>
<td align="center" bgcolor="#FFFFFF"><? echo $rows['view']; ?></td>
<td align="center" bgcolor="#FFFFFF"><? echo $rows['reply']; ?></td>
<td align="center" bgcolor="#FFFFFF"><? echo $rows['datetime']; ?></td>
</tr>
</tbody
<?php
// Exit looping and close connection
}
mysql_close();
?>
<tfoot>
<tr>
<td colspan="6" align="right" bgcolor="#E6E6E6"><strong>Create New Topic</strong> </td>
</tr>
</tfoot>
</table>
</html>

If you don't have a lot of data [less than 100 rows], it is reasonable to load the entire thing with one query and do all the sorting/filtering client-side.
There are tons of great jquery plugins for doing this. Here is a good one I like:
https://datatables.net/
If you want to be scaleable and handle a lot of rows then you don't want to just load all of them at once.
In this case you want to implement a paging pattern with your queries. If you need to do paging then you will also need your query to sort on the backend when the user changes which column they want to sort by.
Rather than reinvent the wheel, especially if you don't feel comfortable rolling your own here, there are lots of tools you can use to do this. This one seems promising: http://blog.drale.com/mysql-table-viewer-with-pagination-and-sorting/

Related

How can I optimally load a web page that is a big table, centering the viewport on a specific row of that table?

I would like to create a web page that is a giant table (a ranking table) with millions of rows.
The table attributes should be the row number, a little image, a username and another number (indicating a score).
When loading the page it should instantly center and starting to load the table from the row associated to the currently logged in user.
So here are my two questions:
What is the best way to center the starting viewport on the current logged in user row?
If an user is in a very low position he would have to wait until all the upper rows are ready, so what should i do to optimize the loading times? Maybe there is a way to load only the rows that are near the viewport of the user?
Here's an example of what I was trying to do (using Bootstrap for the table classes). I was simply putting the id="scrollpoint" on the current username row, so it is centered when i go to table.php#scrollpoint, this surely is not a nice solution, and I don't know at all how to solve the slow loading problems:
<table class="table">
<thead>
<tr>
<th class="sticky-top bg-success" scope="col">#</th>
<th class="sticky-top bg-success" scope="col">IMG</th>
<th class="sticky-top bg-success" scope="col">USERNAME</th>
<th class="sticky-top bg-success" scope="col">POINTS</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
while ($i <= $num_rows) {
if ($_SESSION['username'] == $row['username']) {
?>
<tr class="table-light" id="scrollpoint">
<th scope="row"><?php echo $i; ?></th>
<td><img src="img.png"></td>
<td><?php echo $row['username'] ?></td>
<td><?php echo $row['points'] ?></td>
</tr>
<?php } else { ?>
<tr>
<th scope="row"><?php echo $i; ?></th>
<td><img src="img.png"></td>
<td><?php echo $row['username'] ?></td>
<td><?php echo $row['points'] ?></td>
</tr>
<?php
}
$i++;
}
?>
</tbody>
</table>
Thanks for the help, and sorry if not very clear, english is not my primary language.

datatable with child rows using mysql

In MySQL Database, I have two tables Abc and Pqr. In Abc table there's a unique ID, that ID is used in Pqr table as foreign key.
I want to show the parent element as Abc table data and child rows as Pqr table data with respect to Abc unique ID.
Here is my code:
$sqlGetParents="SELECT * from projectrera order by project_id";
$resultGetParents = $conn->query($sqlGetParents);
?>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Project Name</th>
<th>Builder Id</th>
<th>Location Id</th>
<th>Phase</th>
<th>Status</th>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_array($resultGetParents)) {
echo " <tr>
<td class='details-control'></td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
<td>".$row[3]."</td>
<td>".$row[8]."</td>
<td>".$row[15]."</td>
</tr>";
} ?>
</table>
<div id="test">
<table id='example1'>
<?php
$sqlGetCatWithParent1="SELECT * from info";
$resultGetCatWithParent1 = $conn->query($sqlGetCatWithParent1);
while ($row3 = mysqli_fetch_array($resultGetCatWithParent1)) {
echo " <tr>
<td></td>
<td>".$row3[1]."</td>
<td>".$row3[2]."</td>
<td>".$row3[3]."</td>
</tr>";
}
?>
Why don't you use the JOIN or Subquery on your select statement? I think that would help you since you're using a relational schema on your tables.
Example:
$sqlGetParents =
SELECT abc.*, pqr.* from projectrera abc
LEFT JOIN info pqr on pqr.project_id = abc.project_id
order by project_id
In your HTML table, I suggest to use FOREACH instead of WHILE.
<?php foreach ($row->result() in $resultGetParents) {
echo "<tr>
<td class='details-control'></td>
<td>".<?php echo $row[1]."</td>
<td>".$row[1]."</td>
<td>".$row[3]."</td>
<td>".$row[8]."</td>
<td>".$row[15]."</td>
</tr>";
echo "<tr>
<td></td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
<td>".$row[3]."</td>
</tr>";
} ?>
You can change the $row number based on the results or use text to easily know which columns should be displayed on your table. (i.e $row['project_id'])

Laravel pagination table - sort for one column

I currently have the following:
<table class="table table-striped">
<tr>
<th> Artikelbild </th>
<th> Artikelnummer </th>
<th> Name des Artikels </th>
<th> Beschreibung </th>
<th> Preis </th>
<th> Kategorie </th>
</tr> #foreach($products as $product)
<tr class='clickable-row' <?php if($product->stockCount === 0) echo "style='color:red;'";?>data-href="{{url('/product')}}
<?php echo '/'.$product->id;?>">
<td> <img src="/images/{{$product->imageUrl}}" class="productImageSmall" /> </td>
<td> {{$product->id}} </td>
<td> {{$product->name}} </td>
<td>
<?php if (strlen($product->description) > 30) { $productShortened = substr($product->description, 0, 30) . "[...]"; } else { $productShortened = $product->description; } echo $productShortened; ?> </td>
<td>
<?php echo number_format($product->price, 2, ',', '.');?>€ </td>
<td> {{$product->categoryName}} </td>
</tr> #endforeach
</table>
The $product thing is passed from my controller with the paginate() option.
Now I want that this table is sort-able by one column. So lets say, the user clicks on the "price" (or Preis in german) column on top of the table, then all results should be sorted by the price (from low to high or from high to low), same for the category, for the name and every other column.
How can I do this? Do I have to reload the page and get the data again from the db, but somehow sorted (if yes, how?). Or can I somehow just sort it without reloading it? How can I do this?
Thanks for any help
Building sortable tables is a pretty time-consuming task, so I'd recommend you to use some package. I use this package for building sortable tables.
If you still want to build this functionality by yourself, you can add arguments like ?price=desc to the URL and get these with the request() method. Just an example:
if (request()->has('price')) {
$query = $query->orderBy('price', request('price'));
}
And don't forget to append URL arguments to the pagination links:
{{ $products->appends(['price' => 'desc'])->render() }}

How to fetch the data for one page at a time

I have the problem to fetch the as per number of rows at a time in jQuery DataTables with Bootstrap. Firstly, my code below fetches whole data from the database and starts the pagination.
But I want data loaded for one page at a time.
My PHP code is:
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th> Name</th>
<th>category</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<?php foreach ($datastat as $row) {
?>
<tr>
<td><?php echo $row['fname'];?> <?php echo $row['mname'];?> <?php echo $row['lname'];?></a></td>
<td><?php echo $row['category'];?></td>
<td><?php echo $row['location'];?></td>
</tr>
<?php }?>
</tbody>
<tfoot>
<tr>
<th> Name</th>
<th>category</th>
<th>Location</th>
</tr>
</tfoot>
</table>
My javascript code is:
$(function() {
$('#example1').dataTable({
"bPaginate": true,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"pageLength": 10
});
});
You need to implement server-side processing in order to retrieve one page at a time from the server, see this example.
Luckily DataTables distribution includes PHP class ssp.class.php and sample code that makes it fairly easy to use with PHP.

Mixing code errors

Ok, I have a basic all-in-one page for my user profiles on my site like so:
<?php
if($_GET['p']=='pb'){
echo '<p>pb</p>';
}elseif($_GET['p']=='example2'){
echo '<p>Example Two';
}elseif($_GET['p']=='example1'){
echo '<p>Example One';
}else{
echo '<h3>Page not defined&#59 error!</h3>';
}
?>
I am having issues with some inline javascript though, when I try to add a onclick="location.href='' the php confuses it. I've tried adding \' to the front and back, but it doesn't seem to work, here is what I have:
<?php
if($_GET['p']=='pb'){
echo '<p>pb</p>';
}elseif($_GET['p']=='example2'){
echo '
<h1>Example Link One</h1>
<p>You clicked Example Link One!</p>
<table border="0" cellspacing="15" width="100%">
<tr>
<td bgcolor="grey" onclick="location.href=\''/media/profiles/person/'\'">
<p>HOME</p>
</td>
</tr>
</table>';
}elseif($_GET['p']=='example1'){
echo '
<h1>Example Link One</h1>
<p>You clicked Example Link One!</p>
<table border="0" cellspacing="15" width="100%">
<tr>
<td bgcolor="grey" onclick="location.href=\''/media/profiles/person/'\'">
<p>HOME</p>
</td>
</tr>
</table>';
}else{
echo '<h3>Page not defined&#59 error!</h3>';
}
?>
But I still get several errors, including:
-Use of undefined constant media - assumed 'media'
-Warning: Division by zero
-Notice: Use of undefined constant profiles - assumed 'profiles'
-Notice: Use of undefined constant person - assumed 'person'
So on and so forth.
I know it what it has to do with, but how can I fix it?
Why not just close the PHP tags?
<?php
if($_GET['p']=='pb'){
echo '<p>pb</p>';
}elseif($_GET['p']=='example2'){
?>
<h1>Example Link One</h1>
<p>You clicked Example Link One!</p>
<table border="0" cellspacing="15" width="100%">
<tr>
<td bgcolor="grey" onclick="javascript:location.href='/media/profiles/person/'">
<p>HOME</p>
</td>
</tr>
</table>
<?php
}elseif($_GET['p']=='example1'){
?>
<h1>Example Link One</h1>
<p>You clicked Example Link One!</p>
<table border="0" cellspacing="15" width="100%">
<tr>
<td bgcolor="grey" onclick="javascript:location.href='/media/profiles/person/'">
<p>HOME</p>
</td>
</tr>
</table>
<?php
}else{
echo '<h3>Page not defined&#59 error!</h3>';
}
?>
Also, it would be more elegant to use a design pattern within your application - This application, if you stick with the "design pattern" you're currently using will become a burden to update and maintain.
Your quoting is wrong. You are escaping the first single quote but with another one following imediatly. This second one is interpreted by php as the end of string which is not what you intended. Just remove this 2nd single quotes and it should fix your errors.
echo '
<h1>Example Link One</h1>
<p>You clicked Example Link One!</p>
<table border="0" cellspacing="15" width="100%">
<tr>
<td bgcolor="grey" onclick="location.href=\'/media/profiles/person/\'">
<p>HOME</p>
</td>
</tr>
</table>';
Edit: Also worth mentioning: If you have a string with mixed quotes it is often easier to use heredoc style
$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

Categories