How can i display MYSQL Data using DataTables using While Loop - javascript

How can i display Data from MYSQL table using DataTables
I tried but Top part shown me
Bottom Shows Records from MYSQL table.
I want DataTables to read Mysql data display as shown in the picture below
//bottstrap html code
<div class="panel-body">
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Brand Name</th>
<th>Size</th>
</tr>
</thead>
// php
$record = mysqli_query($con,"SELECT * FROM ts127 ORDER BY Manufacturer");
while ($row = mysqli_fetch_array($record)) {
if()
{
}
elseif ($row['field1']==$XXX)
{
echo'<table style="table-layout:fixed;" class="table table-striped table-bordered table-hover" id="dataTables-example">';
// When i remove the above table code works fine for the first record or first row but other listed as a normal text
echo "<tr'>";
echo "<td style=' width:150px; text-align:left; padding: 10px;vertical-align: middle;'>";echo $row['Brand_Name'];echo"</td>";
echo "<td style='width:110px; text-align:left; vertical-align: middle;'>";echo $row['Size'];"</td>";
....
echo '<tr/></tbody></table>';
}
//JS Code
<script>
$(document).ready(function() {
$('#dataTables-example').DataTable({
responsive: true
});
});
</script>

You mistake was looping the table and tbody, you should be more careful about opening and closing the HTML tags
<?php
$record = mysqli_query($con,"SELECT * FROM ts127 ORDER BY Manufacturer");
echo'<table style="table-layout:fixed;" class="table table-striped table-bordered table-hover" id="dataTables-example">';
echo '<thead>';
echo '<tr>';
echo '<th>Brand Name</th>';
echo '<th>Size/th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while ($row = mysqli_fetch_array($record)) {
if (($row['field1']==$XXX || $row['field1']==$YYY ) && ($row['field2']>=$field1sw && $row['field1']<=$largesw) && ($txtbrand != "" && $size1=="" && $row['field2'] != "" && $row['Brand_Name']!="") )
{
echo "<tr'>";
echo "<td style=' width:150px; text-align:left; padding: 10px;vertical-align: middle;'>";echo $row['Brand_Name'];echo"</td>";
echo "<td style='width:110px; text-align:left; vertical-align: middle;'>";echo $row['Size'];"</td>";
....
echo '</tr>';
}
}
echo '</tbody>';
echo '</table>';
?>
if NOT, I would recommend you to use server-side DataTable

Update this
echo '<tr/></tbody></table>';
To be
echo '</tr>';
Then close the tbody, and table tag outside while loop

Related

How to make an entire row clickable in live search

i am working on a live search.After writing a link in a row using ajax it stop responding
it is a code i have made
//let this page name is index.php
<div>
<input type="search" id="searchterm" name="searchterm" placeholder="Search" >
</div>
<table id="result"></table>
//this is the script of index.page
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"search.php",
method:"post",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#searchterm').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
//this page is search.php
$output='';
if(isset($_POST["query"]))
{
$keyword=mysqli_real_escape_string($conn, $_POST["query"]);
$query="SELECT uid,name,lastname ,profile_pic,about FROM comnet_user_details WHERE uid!='$uid' AND concat_ws(' ',name, lastname) LIKE UPPER('%$keyword%')";
$result=mysqli_query($conn,$query);
if(mysqli_num_rows($result) > 0)
{
while($r=mysqli_fetch_array($result))
{
$nm=$r["name"]." ".$r["lastname"];
$profilepic=$r["profile_pic"];
$about=$r["about"];
$id=$r["uid"];
$output .=
'<table class="msgtab" id="fetchresult">
<tr class="trow" onclick="location.href="conversation.php?value='.$id.'"">
<td class="msg-col-1"><img src="images/profilepic/'.$r["profile_pic"].'alt="Avatar" class="circlemsg"></td>
<td class="msg-col-2">
<h5 class="msgheading">'.$nm.'</h5>
<p class="msgcontent">'.$about.'</p>
</td>
</tr>;
}
echo $output;
}
I expect live search result row should be clickable and clicking on a particular result or row it should lead to the desire page, but my live search results link is not working
There is a typo in <img src="images/profilepic/'.$r["profile_pic"].'alt="Avatar" class="circlemsg">
It need to be <img src="images/profilepic/'.$r["profile_pic"].'" alt="Avatar" class="circlemsg">
Also, profile_pic does have also the extension (i.e: 'jpg, png') ?
Edit:
Could you replace the piece of code with this one (hope it will work):
- create a table
- in the while loop -> create every row <tr>
- then close the table
if(mysqli_num_rows($result) > 0) {
$output = '<table class="msgtab" id="fetchresult">';
while($r=mysqli_fetch_array($result))
{
$nm=$r["name"]." ".$r["lastname"];
$profilepic=$r["profile_pic"];
$about=$r["about"];
$id=$r["uid"];
$output .=
'<a href="conversation.php?value='.$id.'">
<tr class="trow">
<td class="msg-col-1"><img src="images/profilepic/'.$r["profile_pic"].'" alt="Avatar" class="circlemsg"></td>
<td class="msg-col-2">
<h5 class="msgheading">'.$nm.'</h5>
<p class="msgcontent">'.$about.'</p>
</td>
</tr>
</a>';
}
$output .= '</table>';
echo $output;
}
Ok..After working many times on it I have found a solution of it, and which is working for me. It is like that
if(mysqli_num_rows($result) > 0) {
$output = '<table class="msgtab" id="fetchresult">';
while($r=mysqli_fetch_array($result))
{
$nm=$r["name"]." ".$r["lastname"];
$profilepic=$r["profile_pic"];
$about=$r["about"];
$id=$r["uid"];
$output .=
'<table class="msgtab" id="fetchresult">
<tr class="trow" onclick=location.href="conversation.php?value='.$id.'">
<td class="msg-col-1"><img src="images/profilepic/'.$r["profile_pic"].'" alt="Avatar" class="circlemsg"></td>
<td class="msg-col-2">
<h5 class="msgheading">'.$nm.'</h5>
<p class="msgcontent">'.$about.'</p>
</td>
</tr>';
}
$output .= '</table>';
echo $output;
}
After this, my entire row is clickable now.

change the column in csv using php

in the code i used csv file in which i want to edit the rows of 3rd coulmn as want to make them a http link by using tag but i cant do that. right now the code chowing only the link but i want to make them hyperlink
<html>
<head>
</head><body>
<table width="10%" cellpadding="1" cellspacing="0" border="1" ;">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
<?php
$f = fopen("http://localhost/csv/cr.csv", "r");
while (($line = fgetcsv($f)) !== false) {
echo "<tr>";
$data = count($line);
foreach ($line as $cell) {
echo "<td>" . htmlspecialchars($cell) . "</td>";
}
echo "</tr>\n";
}
fclose($f);
?>
</tr>
</thead>
</table>
</body>
</head>
try:
<?php
$f = fopen("http://localhost/csv/cr.csv", "r");
while (($line = fgetcsv($f)) !== false) {
if (!isset($line[2])) {
continue;
}
echo "<tr><td><a href='url'>" . htmlspecialchars($line[2]) . "</a></td></tr>";
}
fclose($f);
?>

How can I show a hidden div below each row using bootstrap table?

In my admin panel I've a user page where all users are showing using Bootstrap Table with sorting option, pagination option.
Now I want to show more information about a user below each row when I click on a whole row then a div box will appear with more information.
How can i show this hidden div box below the each row ?
Javascript I'm using in html head section:
<script type="text/javascript" language="javascript" src="media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="media/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$('#example').dataTable();
$('#example tbody').on('click', 'tr', function () {
var name = $('td', this).eq(0).text();
} );
} );
</script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap-theme.min.css">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
Php & Html code I'm using in the html body section
<?php
$getUser = mysql_query("select * from members ORDER BY user_id DESC");
$num = mysql_num_rows($getUser);
?>
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Company</th>
<th>Position</th>
<th>Status</th>
<th>Kit type</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
while($search_result = mysql_fetch_array($getUser)){
$i++;
$uid = (int) $search_result['user_id'];
$email = $search_result['email'];
$fname = $search_result['fname'];
$lname = $search_result['lname'];
$company = $search_result['company'];
$position = $search_result['position'];
$status = $search_result['status'];
echo "<tr>";
echo "<td class='row' $class valign='top'>$fname</td>";
echo "<td class='row' $class valign='top'>$lname</td>";
echo "<td class='row' $class valign='top'>$company</td>";
echo "<td class='row' $class valign='top'>$position</td>";
echo "<td class='row' $class valign='top'>$status</td>";
echo "<td class='row' $class valign='top'>$kittype</td>";
echo "</tr>";
}
?>
</tbody>
</table>

How to dynamically populate table based on data

This is my HTML code
<table data-role="table" id="movie-table" data-filter="true" data-input="#filterTable-input" class="ui-responsive">
<thead>
<tr>
<th data-priority="1">Rank</th>
<th data-priority="persist">Player Name</th>
<th data-priority="2">Record</th>
<th data-priority="3"><abbr title="Rotten Tomato Rating">Points</abbr></th>
<th data-priority="4">Highlight</th>
</tr>
</thead>
<tbody >
<div id="table"></table>
</tbody>
</table>
**This is my Javascript/Jquery**
$( document ).ready(function()
{
$.get('./php/rank.php', function(data)
{
$('#table').html(data);
}).error(function() {
$('#table').append('An error has occured');
} ).success (function(){
$('#table').append('');
})
});
**This is my php**
echo "<tr>";
echo "<th>". $row1['points']."<td/>";
echo "<td>". $row1['points']."<td/>";
echo "<td>". $row1['points']."<td/>";
echo "<td>". $row1['points']."<td/>";
echo "<td>". $row1['points']."<td/>";
echo "</tr>";
What I am trying to accomplish is to populate the table based on registered users. I
tried to echo the complete table - no success(I'm using JQuery Mobile) So I thought maybe I can Just Echo the th and td tags that will vary. Any suggestions would be greatly appreciated, maybe I'm just going about this the wrong way. Thanks
You are not closing your tags properly. Moreover, there is no need for a div insde tbody (I don't know if it's even allowed). Try with this corrected code:
<table data-role="table" id="movie-table" data-filter="true" data-input="#filterTable-input" class="ui-responsive">
<thead>
<tr>
<th data-priority="1">Rank</th>
<th data-priority="persist">Player Name</th>
<th data-priority="2">Record</th>
<th data-priority="3"><abbr title="Rotten Tomato Rating">Points</abbr></th>
<th data-priority="4">Highlight</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
**This is my Javascript/Jquery**
$( document ).ready(function()
{
$.get('./php/rank.php', function(data)
{
$('#movie-table tbody').html(data);
}).error(function() {
$('#movie-table tbody').append('An error has occured');
} ).success (function(){
$('#movie-table tbody').append('');
})
});
**This is my php**
echo "<tr>";
echo "<th>". $row1['points']."</th>";
echo "<td>". $row1['points']."</td>";
echo "<td>". $row1['points']."</td>";
echo "<td>". $row1['points']."</td>";
echo "<td>". $row1['points']."</td>";
echo "</tr>";
Edit: and of course you don't want to show the field "points" in all of the five columns.
I solved it. In php you have to echo the complete table.
echo "<table data-role='table' id='movie-table' data-filter='true' data-input='#filterTable-input' class='ui-responsive'>";
echo "<thead>";
echo "<tr>";
echo "<th data-priority='1'>Rank</th>";
echo "<th data-priority='persist'>Player Name</th>";
echo "<th data-priority='2'>Record</th>";
echo "<th data-priority='3'><abbr title='Rotten Tomato Rating'>Points</abbr></th>";
echo "<th data-priority='4'>Highlight</th>";
echo "</tr>";
echo "</thead>";
while($row1 = mysql_fetch_array($result1)){
echo "<tbody>";
echo "<tr>";
echo "<th>1</th>";
echo "<td>Kentwan</td>";
echo "<td>10-0</td>";
echo "<td>1000</td>";
echo "<td>test</td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
Try something like this:
<table data-role="table" id="movie-table" data-filter="true" data-input="#filterTable-input" class="ui-responsive">
<thead>
<tr>
<th data-priority="1">Rank</th>
<th data-priority="persist">Player Name</th>
<th data-priority="2">Record</th>
<th data-priority="3"><abbr title="Rotten Tomato Rating">Points</abbr></th>
<th data-priority="4">Highlight</th>
</tr>
</thead>
<tbody id='tab_body'>
</tbody>
</table>
** your Javascript/Jquery**
$( document ).ready(function()
{
$.get('./php/rank.php', function(data)
{
$('#tab_body').html(data);
})
}

Exclude Specific Columns when exporting data from HTML table to excel

I am using this script for exporting data from HTML table to Excel.
<script>
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
I found this here
but when i export this data it includes all columns in HTML table as expected to do. but my last row contains some icons that i don't want to export to excel.
<div class="row" style="margin-left:20px;">
<div class="grid_4">
<div class="da-panel collapsible">
<input type="button" class="btn btn-success" onclick="tableToExcel('testTable', 'W3C Example Table')" value="Export to Excel" style="float:right">
<div class="da-panel-content">
<div class="da-panel-title" style="border-top:1px solid #ccc;border-bottom:1px solid #ccc">
<h3 style="padding-left:10px;font-weight:bold;">Staff Training Information</h3></div>
<table class="da-table da-ex-datatable-numberpaging" id="testTable" width="100%">
<thead width="100%">
<tr>
<th width="10%">Staff ID</th>
<th width="10%">Name</th>
<th width="10%">Location</th>
<th width="10%">POCT Test</th>
<th width="10%">Initial Training Date</th>
<th width="10%">Annual Competency Date</th>
<th width="10%">Competency Type</th>
<th width="1%">Next Competency Date</th>
<th width="39%">Action</th>
</tr>
</thead>
<tbody width="100%">
<?php
include_once('database.php');
$pdo = Database::connect();
$sql = 'SELECT * FROM competency';
foreach ($pdo->query($sql) as $row) {
$id = $row['staff_id'];
echo '<tr>';
echo '<td width="10%">'. $row['staff_id'] . '</td>';
$sql1 = "SELECT *FROM staff WHERE StaffID='$id'";
foreach($pdo->query($sql1) as $res)
{
echo '<td width="10%">'. $res['StaffName'] . '</td>';
}
echo '<td width="10%">'. $row['location'] . '</td>';
?>
<td width="10%">
<?php
$s = $row['poct_test'];
$val = explode(" ",$s);
for ($i=0; $i<sizeof($val); $i++)
{
$v = $val[$i];
echo $v."<br/>";
}
?>
</td>
<?php
echo '<td width="10%">'. $row['date_of_initial_training'] . '</td>';
echo '<td width="10%">'. $row['annual_competency'] . '</td>';
echo '<td width="10%">'. $row['type_of_competency'] . '</td>';
echo '<td width="1%">'. $row['next_competency'] . '</td>';
echo '<td width="39%">';
echo '<img src="images/ic_zoom.png" height="16" width="16" />';
echo ' ';
echo '<img src="images/icn_edit.png"/>';
echo ' ';
?>
<img src="images/icn_logout.png"/>
<?php
echo '</td>';
echo '</tr>';
}
Database::disconnect();
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
As shown in code that last 3 echo contains update/delete icons. I just want to exclude Action column when exporting the table content in excel.
Any help would be highly appreciated.
You can use selectors from jQuery, clone of your table in memory then remove elements you don't want with appropriate selector.
var $table = $('#testTable').clone();
$table = filterNthColumn($table, 9); //remove Action column
function filterNthColumn($table, n){
return $table.find('td:nth-child('+n+'), th:nth-child('+n+')').remove();
}
make a hidden div under the table
<div class="exportData"> </div>
Then on click of the export button call export.php through ajax and put the result into exportData div. Then you can call your print script on the new data brought.
$.post( "export.php", function( data ) {
$( ".result" ).html( data );
});
Copy past your for loop on export.php and delete the two cols.
I think you can just clone the table firstly, remove the action column, and "tableToExcel" the cloned table.
To make the column removing easier, add class "action_th" to action th, and class "action_td" to action td.
Then it's like this,
var exTable = $('#testTable').clone();
//remove the action th/td
exTable.find('.action_th, .action_td').remove();
//then tableToExcel(exTable, ..
This works for me -
$('#divTableContainer').clone().find('table tr th:nth-child(7),table tr td:nth-child(7)).remove().end().prop('outerHTML')

Categories