datatable with child rows using mysql - javascript

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'])

Related

Passing of data from main page to php query inside a modal

I have a dataTable that passes it's row to a modal. Will it be possible to pass it directly to the php page using the same modal script?
This is my main_page.php
<table id="example1" class="table table-bordered">
<thead>
<th>Reference No</th>
<th>Finger Scan No</th>
<th>Date From</th>
<th>Date To </th>
<th>Tools </th>
</thead>
<tbody>
<?php
$user = $user['fingerscanno'];
$sql = "
SELECT
payroll.payrollno AS payrollno,
payroll.referenceno AS referenceno,
payroll.fingerscanno AS fingerscanno,
payroll.datefrom AS datefrom,
payroll.dateto AS dateto,
USERINFO.USERID,
USERINFO.BADGENUMBER
FROM
payroll,
USERINFO
WHERE
USERINFO.BADGENUMBER = payroll.fingerscanno AND
payroll.fingerscanno='$user'
";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
echo "
<tr>
<td>".$row['referenceno']."</td>
<td>".$row['fingerscanno']."</td>
<td>".$row['datefrom']."</td>
<td>".$row['dateto']."</td>
<td>
<button class='btn btn-success btn-sm edit btn-flat' data-id='".$row['referenceno']."'><i class='fa fa-edit'></i> Proof of Attendance</button>
<button class='btn btn-danger btn-sm delete btn-flat' data-id='".$row['referenceno']."'><i class='fa fa-edit'></i> Payslip Summary</button>
</td>
</tr>
";
}
?>
</tbody>
</table>
<?php include 'includes/mymodal.php'; ?>
This is the modal function
$(function(){
$("body").on('click', '.edit', function (e){
e.preventDefault();
$('#edit').modal('show');
var id = $(this).data('id');
getRow(id);
});
This is the modal page
mymodal.php
<div class="modal fade" id="edit">
<input type="hidden" class="decid" id="id" name="id">
<table id="example2" class="table table-bordered">
<thead>
<th>Schedule Date</th>
<th>Schedule Name</th>
<th>Recorded In</th>
<th>Recorded Out</th>
<th>Day Count</th>
<th>Day Value</th>
<th>N.D. Value</th>
<th>Leave Count</th>
<th>R.H. Count</th>
<th>R.H. Value</th>
</thead>
<tbody>
<?php
$sql = "SELECT fingerscanno, scheduledate, schedulename, recordin, recordout, noofdays, rate, nightdifferential, leaveday, regularholiday, specialholiday, referenceno
FROM payrollrecords WHERE fingerscanno='$user' and referenceno='$id'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
echo "
<tr>
<td>".$row['scheduledate']."</td>
<td>".$row['schedulename']."</td>
<td>".$row['recordin']."</td>
<td>".$row['recordout']."</td>
<td>".$row['noofdays']."</td>
<td>".$row['rate']."</td>
<td>".$row['nightdifferential']."</td>
<td>".$row['leaveday']."</td>
<td>".$row['regularholiday']."</td>
<td>".$row['specialholiday']."</td>
</tr>
";
}
?>
</tbody>
</table>
</div>
My question is, how will I pass this into the table? So that the variable referenceno='$id' will receive the value from the main page.
You need to use AJAX.
Ajax is a javascript methodology that allows you to exchange information with a back-end PHP file, just as you are attempting to do.
The AJAX code block will send data to the mymodal.php file, the mymodal.php file will do the MySQL lookup and create the HTML, then echo a string variable (which could be a json object or it could be the HTML that you built in your while loop) back to the main page. The AJAX code block will receive the data echo'd out from the PHP file inside the .done() function and, also in that function, you can modify the DOM to inject the new data. To the user, it will look like they clicked on an element with class edit and the data just appeared in the modal.
Note that you do not include the mymodal.php file in your main_file.php page, because the AJAX code block knows how to communicate with that file.
You will need to add the HTML structure for the modal to the bottom of your main page (note that it is initially set to display:none):
<style>
#lamodal{display:none;position:fixed;width:100vw;height:100vh;background:black;opacity:0.8;}
#mdl_inner{width:60%;height:40%;}
.myflex{display:flex;align-items:center;justify-content:center;}
</style>
<div id="lamodal" class="myflex">
<div id="mdl_inner"></div>
</div><!-- #lamodal -->
Your javascript (AJAX) will look something like this:
$(function(){
$("body").on('click', '.edit', function (e){
e.preventDefault();
var id = $(this).data('id');
$.ajax({
type: 'post',
url: 'mymodal.php',
data: 'userid=id'
}).done(function(d){
//console.log('d: '+d);
$('#mdl_inner').html(d);
$('#lamodal').show();
});
});
});
Your mymodal.php file would be changed to look like this:
<?php
$sql = "SELECT fingerscanno, scheduledate, schedulename, recordin, recordout, noofdays, rate, nightdifferential, leaveday, regularholiday, specialholiday, referenceno
FROM payrollrecords WHERE fingerscanno='$user' and referenceno='$id'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$out = '
<table id="example2" class="table table-bordered">
<thead>
<th>Schedule Date</th>
<th>Schedule Name</th>
<th>Recorded In</th>
<th>Recorded Out</th>
<th>Day Count</th>
<th>Day Value</th>
<th>N.D. Value</th>
<th>Leave Count</th>
<th>R.H. Count</th>
<th>R.H. Value</th>
</thead>
<tbody>
';
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
$out .= '
<tr>
<td>".$row['scheduledate']."</td>
<td>".$row['schedulename']."</td>
<td>".$row['recordin']."</td>
<td>".$row['recordout']."</td>
<td>".$row['noofdays']."</td>
<td>".$row['rate']."</td>
<td>".$row['nightdifferential']."</td>
<td>".$row['leaveday']."</td>
<td>".$row['regularholiday']."</td>
<td>".$row['specialholiday']."</td>
</tr>
';
}
$out .= '
</tbody>
</table>
';
echo $out;
?>
Note how we are constructing a string variable and building it through concatination. When done, just echo $out and the newly-constructed HTML will appear in the .done() function of your AJAX code block.
See these additional AJAX examples and explanations:
http://www.jayblanchard.net/basics_of_jquery_ajax.html
Simple Like/Unlike text button - adding ajax etc
pass var to bootstrap modal where php will use this value

Fetch table row data as per the selected checkbox

I am using Material Design Lite to create a table and I am inserting rows dynamically using php.
The material design lite has provided checkboxes for each row. Now, I want to use the selected row's data on a button click. Does anyone have any idea how to do that?
Here is the code :
<table class="mdl-data-table mdl-js-data-table mdl-data-table--selectable mdl-shadow--2dp" id="sanctionedTable">
<thead>
<tr>
<th class="mdl-data-table__cell--non-numeric">Name</th>
<th class="mdl-data-table__cell--non-numeric">Registration No.</th>
<th class="mdl-data-table__cell--non-numeric">Amount</th>
</tr>
</thead>
<tbody>
<?php
$temp = "";
while($row = mysqli_fetch_assoc($result))
{
$temp="<tr><td>".$row["name"]."</td><td>".$row["regno"]."</td><td>".$row["amount"]."</td></tr>";
echo $temp;
}
?>
</tbody>
</table>
You can use something like this using jquery:
$('tr').click(function(){
alert("Name:"+$(this).children('td:nth-child(1)').html()+",Registration nio:"+$(this).children('td:nth-child(2)').html()+",Amount:"+$(this).children('td:nth-child(3)').html());
});
This fetches the information in each row.

jquery filter on table works first time but after that hides all rows

I've created a filter to show only rows containing td's with the value selected from a dropdown. The filter works fine first time but second time i run it, all rows dissapear and I cant figure out why.
This is my filter:
$(document).ready(function(){
$('select[name=selectedName]').change(function() {
$('tr').filter(function () {
return $(this).find('td.userName').filter(function () {
return $(this).text().indexOf($('select[name=selectedName]').val()) == -1;
}).length;
}).hide();
});
});
The drop down:
$query = "SELECT user_name FROM users";
$result = mysql_query($query); ?>
<select name="selectedName" id="userSelected">
<option value="" disabled selected>user name</option>
<?php while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
<option value="<?php echo $line['user_name'];?>">
<?php echo $line['user_name'];?>
</option>
<?php } ?>
</select>
And finally the creation of the table:
<table class="table table-bordered table-hover" ng-controller="tableCtrl">
<thead>
<th>user name</th>
<th>script name</th>
<th>cron format<span class="glyphicon glyphicon-question-sign"></span></th>
<th>schedule last update</th>
<th>next execution time</th>
<th>script exec</th>
</thead>
<tbody ng-repeat="(user_id,script_id) in data">
<tr ng-repeat="(script_id, cron_format) in script_id">
<td class="userName">{{user(user_id)}}</td>
<td class="scriptName">{{script(script_id)}}</td>
<td class="cronFormat"><span contenteditable="true" ng-repeat="l in letters(cron_format) track by $index">{{l}}</span></td>
<td>{{compare(user_id,script_id,cron_format)[0]}}</td> <!--[0] represents scheduler last update-->
<td>{{compare(user_id,script_id,cron_format)[1]}}</td> <!--[1] represents next execution time-->
<td>{{compare(user_id,script_id,cron_format)[2]}}</td> <!--[2] represents script_exec-->
</tr>
</tbody>
</table>
Any idea why is it happening? Thanks for helping...
UPDATE
i added $('tr').show(); and function works except, how can i add value in dropdown to show the all table/cancel the filter?
You take care of hiding rows, but you never show them back. This is why your table sooner or later will have all rows invisible.

Filter SQL Data on HTML Table

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/

jQuery drag & drop table rows sort not working

I wanted to make a script to order some rows from a database with drag & drop. The rows are displayed in a table, and I drag and drop rows to reorder them. Each tr have the row id from database. When I drag and drop a row, jquery serialize the table content and sends it to php to save rows position.
What could be the problem that rows position are not saved in db?
Table with rows:
$select_categories = mysqli_query($db_connect, "SELECT `id`, `title` FROM `categories` ORDER BY `category_order` ASC") or die(mysqli_error());
if(mysqli_num_rows($select_categories) != 0)
{
echo '<table cellpadding="0" cellspacing="0" class="manage_content" id="sort_rows" align="center">';
while($category = mysqli_fetch_assoc($select_categories))
{
echo '
<tr id="row-'.$category['id'].'">
<td width="700">'.$category['title'].'</td>
<td>Delete</td>
</tr>
';
}
echo '</table>';
}
jQuery
$("#sort_rows tbody").sortable({
cursor: 'move',
delay: 180,
update: function()
{
var rowsOrder = $(this).sortable("serialize");
$.post("ajax_actions.php", { action:'change_rows_order', table:'categories', order:'category_order', rows_order:rowsOrder } );
}
}).disableSelection();
AJAX
if(isset($_POST['action']) && $_POST['action'] == 'change_rows_order')
{
$order_no = 1;
foreach($_POST['rows_order'] as $row_id)
{
$update_order = mysqli_query($db_connect, "UPDATE `".clear_tags($_POST['table'])."` SET `".clear_tags($_POST['order'])."` = '".$order_no."' WHERE `id` = '".$row_id."'") or die(mysqli_error());
$order_no++;
}
}
HTML
<table cellpadding="0" cellspacing="0" class="manage_content" id="sort_rows" align="center">
<tr id="row-10">
<td width="700">Editorial</td>
<td>Delete</td>
</tr>
<tr id="row-11">
<td width="700">Fashion</td>
<td>Delete</td>
</tr>
<tr id="row-12">
<td width="700">Street Style</td>
<td>Delete</td>
</tr>
<tr id="row-13">
<td width="700">Portraits</td>
<td>Delete</td>
</tr>
<tr id="row-14">
<td width="700">Clothing</td>
<td>Delete</td>
</tr>
</table>
I solved the problem. I followed the tutorial here: http://www.webresourcesdepot.com/dynamic-dragn-drop-with-jquery-and-php/

Categories