Community, I currently have some pagination on my page to help users page through logged tickets. To help with this, I have two table cells with Next and Previous in each respectively. Right now, when a user clicks either, it adds +1 or -1 to a JS counter that AJAX's a string. Then, I have my pagination that either goes to the next or previous 15 items in my mysql database. I wrote my JS so that if the counter is less than 1 it will go back to one. That way they dont have to repeatedly click the next button to view tickets. I'm trying to figure out a way to do that from the other end, where if the end of the result list is blank, or no more results are available, it will stay at the last counter.
PhP including initial table setup and string variable
include 'Search_Var.php'; //This file is used to build $sequel.
//$sequel is a string built by user selected search options
echo '<div style="display: none" id="Search_Var">'.$sequel.'</div>
<div class="container" style="clear: both;">
<fieldset>
<legend class="legend1"><h2>   Results   </h2></legend>
<div style="padding-top: 5px;">
<span id="page">';
include 'Search_Tickets.php'; // This file builds a table to show the first 15 results
// It also displays the total number of tickets found
// in the database matching the search query
echo '</span>';
if($openTicketsCount!=0) {include '********/***********/PreviousNext.inc.php';};
//If no tickets are available the Previous and Next boxes won't appear.
</fieldset>
</div>
</div>
';
Javascript
var count = 1;
$(window).on('load', function() {
var id = document.getElementById( "Search_Var" ).innerText;
$('.page').on('click', function() {
var page = $(this).html();
if(page == "Next")
{
count = count + 1;
}
if(page == "Previous")
{
count = count - 1;
}
if(count < 1)
{
count = 1;
}
$.get("/*******/********/Search_Pagination.inc.php?count_id=" + count + "&search_id=" + id, function(data) {
$('#page').html(data);
});
});
});
Finally, the pagination
$start = 0;
$per_page = 15;
$page = $_GET['selection_id'];
$_SESSION['role_id'] = $_GET['role_id'];
$_SESSION['bus_id'] = $_GET['bus_id'];
$_SESSION['dept_id'] = $_GET['dept_id'];
if($page <= 1)
{
$start = 0;
}
else
{
$start = $page * $per_page - $per_page;
}
$get_openTickets = $search;
$openTicketsCount = mysql_num_rows(mysql_query($get_openTickets));
$num_rows = mysql_num_rows(mysql_query($get_openTickets));
$num_pages = $num_rows / $per_page;
$get_openTickets .= " LIMIT $start, $per_page";
if($openTicketsCount !=true)
{
echo '
<td colspan = "9">No open tickets were found!</td>
';
}
else
{
$result = mysql_query($get_openTickets);
echo '
<table class="openTickets" width="1150px" border="0px" padding="0px">
<tr>
<th scope="col">ID</th>
<th scope="col" style="width:75px;">PRIORITY</th>
<th scope="col">CALLER /<br />DEPARTMENT</th>
<th scope="col">COMPANY NAME /<br />SALES REP</th>
<th scope="col" style="width:75px;">CREATED<br />ON</th>
<th scope="col" style="width:75px;">LAST<br />UPDATED</th>
<th scope="col" style="width:75px;">SOURCE</th>
<th scope="col">USER</th>
<th scope="col">CATEGORY /<br />SUBCATEGORY</th>
</tr>
';
while(($openTicket = mysql_fetch_assoc($result)))
{
echo'
<tr>
<td>'.$openTicket['call_id'].'</td>
<td style="width:75px;">'.$openTicket['priority_name'].'</td
<td>'.$openTicket['caller_name'].'<br />'.$openTicket['caller_dept'].'</td>
<td>'.$openTicket['cust_name'].'<br />'.$openTicket['cust_rep'].'</td>
<td style="width:75px;">'.$openTicket['created_on'].'</td>
<td style="width:75px;">'.$openTicket['updated_on'].'</td>
<td style="width:75px;">'.$openTicket['source_name'].'</td>
<td>'.$openTicket['created_by'].'</td>
<td>'.$openTicket['cat_name'].'<br />'.$openTicket['subcat_name'].'</td>
</tr>';
}
echo '
<tr>
<th colspan="9" style="text-align:right;">Total Open Ticket(s): '.$openTicketsCount.' </th>
</tr>
</table>';
}
have a look below
$start = 0;
$per_page = 15;
$page = $_GET['selection_id'];
$_SESSION['role_id'] = $_GET['role_id'];
$_SESSION['bus_id'] = $_GET['bus_id'];
$_SESSION['dept_id'] = $_GET['dept_id'];
if($page <= 1)
{
$start = 0;
}
else
{
$start = $page * $per_page - $per_page;
}
$get_openTickets = $search;
$openTicketsCount = mysql_num_rows(mysql_query($get_openTickets));
$num_rows = mysql_num_rows(mysql_query($get_openTickets));
$num_pages = $num_rows / $per_page;
$get_openTickets .= " LIMIT $start, $per_page";
if($openTicketsCount !=true)
{
echo '
<td colspan = "9">No open tickets were found!</td>
';
}
else
{
$result = mysql_query($get_openTickets);
echo '<input type="hidden" value="'.$num_pages.'" id="pageCount"/>
<table class="openTickets" width="1150px" border="0px" padding="0px">
<tr>
<th scope="col">ID</th>
<th scope="col" style="width:75px;">PRIORITY</th>
<th scope="col">CALLER /<br />DEPARTMENT</th>
<th scope="col">COMPANY NAME /<br />SALES REP</th>
<th scope="col" style="width:75px;">CREATED<br />ON</th>
<th scope="col" style="width:75px;">LAST<br />UPDATED</th>
<th scope="col" style="width:75px;">SOURCE</th>
<th scope="col">USER</th>
<th scope="col">CATEGORY /<br />SUBCATEGORY</th>
</tr>
';
while(($openTicket = mysql_fetch_assoc($result)))
{
echo'
<tr>
<td>'.$openTicket['call_id'].'</td>
<td style="width:75px;">'.$openTicket['priority_name'].'</td
<td>'.$openTicket['caller_name'].'<br />'.$openTicket['caller_dept'].'</td>
<td>'.$openTicket['cust_name'].'<br />'.$openTicket['cust_rep'].'</td>
<td style="width:75px;">'.$openTicket['created_on'].'</td>
<td style="width:75px;">'.$openTicket['updated_on'].'</td>
<td style="width:75px;">'.$openTicket['source_name'].'</td>
<td>'.$openTicket['created_by'].'</td>
<td>'.$openTicket['cat_name'].'<br />'.$openTicket['subcat_name'].'</td>
</tr>';
}
echo '
<tr>
<th colspan="9" style="text-align:right;">Total Open Ticket(s): '.$openTicketsCount.' </th>
</tr>
</table>';
}
And then change this
var count = 1;
$(window).on('load', function() {
var id = document.getElementById( "Search_Var" ).innerText;
$('.page').on('click', function() {
var page = $(this).html();
if(page == "Next")
{
count = count + 1;
}
if(page == "Previous")
{
count = count - 1;
}
if(count < 1)
{
count = 1;
}
if(count > parseInt( $("#pageCount").val()))
{
count = parseInt($("#pageCount").val());
}
$.get("/*******/********/Search_Pagination.inc.php?count_id=" + count + "&search_id=" + id, function(data) {
$('#page').html(data);
});
});
});
Edit:
It might be that the page count is not an integer so just check that the page count returns a valid integer, also added parseInt, it might be the reason why it was not working
I dont know why "Add Comment" is not shown for me,
But I wanted to say dont use functions mysql_*
Try using something like PDO
Related
I have a page fetching multiple data for a table. One of the data columns has a date and time value
from where a countdown timer runs.Each row has it's own countdown timer and it's working well.
However after I included javascript code to refresh the table after every 10 seconds and get new records inserted into the database, the page breaks and only displays the first timer in the countdown column timers. The tables uses datatable js library. Any recommended way that can enable the page div container to load the page correctly with javascript setinterval function will be highly appreciated.
The code below is what I use for refreshing the page div container
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
cache: false
});
setInterval(function() {
var url = "loaded.php";
$('#loaded_orders').load(url + " #loaded_orders").fadeIn('slow');
}, 10000);
});
This code I use to start the count down timer in the table columns. The table is wrapped in the div with the id "loaded_orders"
<table class="table table-bordered table stripped table hover" data-order='[[ 0, " desc" ]]' id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID </th>
<th>Order No</th>
<th>Order title</th>
<th>Actual Deadline</th>
<th>Assigned Writer</th>
<th>Inserted By</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID </th>
<th>Order No.</th>
<th>Order title</th>
<th>Actual Deadline</th>
<th>Assigned Writer</th>
<th>Inserted By</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
<?php while ($row = $result->fetch_assoc()) {
//echo json_encode($row);
?>
<tr>
<td><?= $row['id']; ?> </td>
<td><?= $row['orderno']; ?></td>
<td> <?= $row['ordertitle']; ?> </td>
<td>
<script src="./js/countdown.js" type="text/javascript"></script>
<script>
u_d = ("d" + "<?= $row['id']; ?>");
u_h = ("h" + "<?= $row['id']; ?>");
u_m = ("m" + "<?= $row['id']; ?>");
u_s = ("s" + "<?= $row['id']; ?>");
ty = "<?= $row['actdeadline']; ?>";
document.write("<div class='writerDeadl'><p class='timer'><span id='" + u_d + "'></span> Day(s) <span id='" + u_h + "'></span>:<span id='" + u_m + "'></span>:<span id='" + u_s + "'></span></p></div>");
countdown(ty, u_d, u_h, u_m, u_s);
</script>
</td>
<td><?= $row['asswriter']; ?> </td>
<td><?= $row['inserted_by']; ?></td>
<td>Details |
del<i class="fas fa-trash "></i> |
Edit<i class="fas fa-edit"></i> |
send<i class="fas fa-paper-plane"></i> |
cancel
</td>
</tr>
<?php } ?>
</tbody>
</table>
The code below is for countdown.js file
function countdown(endDate, uid_d, uid_h, uid_m, uid_s) {
let timer, days, hours, minutes, seconds;
endDate = new Date(endDate).getTime();
if (isNaN(endDate)) {
return;
}
if (uid_d != null) {
timer = setInterval(calculate, 1000);
}
function calculate() {
let startDate = new Date();
startDate = new Date(
startDate.getUTCFullYear(),
startDate.getUTCMonth(),
startDate.getUTCDate(),
startDate.getUTCHours(),
startDate.getUTCMinutes(),
startDate.getUTCSeconds()
);
let timeRemaining = parseInt((endDate - startDate.getTime()) / 1000);
if (timeRemaining >= 0) {
days = parseInt(timeRemaining / 86400);
timeRemaining = timeRemaining % 86400;
hours = parseInt(timeRemaining / 3600);
timeRemaining = timeRemaining % 3600;
minutes = parseInt(timeRemaining / 60);
timeRemaining = timeRemaining % 60;
seconds = parseInt(timeRemaining);
document.getElementById(uid_d).innerHTML = parseInt(days, 10);
document.getElementById(uid_h).innerHTML = ("0" + hours).slice(-2);
document.getElementById(uid_m).innerHTML = ("0" + minutes).slice(-2);
document.getElementById(uid_s).innerHTML = ("0" + seconds).slice(-2);
} else {
return;
}
}
}
I discovered the only way to refresh datatables with setInterval without losing datatbles functionality is to use json data then draw the table. After ding that everything is working well.
I have implemented php function which fetches results and displays them using pagination. Also, I have tried to set on click listener in Jquery to remove active class from the previously selected page and add it to the new one.
However, it correctly switches to a different page but it does not change active class. I am using simplePagination.js
if (isset($_GET["list"])) {
$page = $_GET["list"];
} else {
$page=1;
}
$limit = 10;
$start_from = ($page-1) * $limit;
$query = "SELECT * FROM users WHERE sender_id = '".$_SESSION['id']."' ORDER BY date_time DESC LIMIT $start_from, $limit";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) == 0) {
echo "error";
} else {
echo '<br /><table class="table table-hover">
<thead>
<tr>
<th scope="col"></th>
<th scope="col">Message</th>
<th scope="col">Date</th>
</tr>
</thead>
<tbody>';
while ($row = mysqli_fetch_assoc($result)) {
echo '<tr>
<th scope="row"></th>
<td>View Message</td>
<td>'.$row['date_time'].'</td>
</tr>';
}
echo '</tbody>
</table>';
$query = "SELECT COUNT(message_id) FROM inbox";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_row($result);
$total_records = $row[0];
$total_pages = ceil($total_records / $limit);
$paginationLink = "<nav><ul class='pagination'>";
for ($i = 1; $i <= $total_pages; $i++) {
$paginationLink .= "<li><a href='?page=inbox_sent&list=".$i."'>".$i."</a></li>";
};
echo $paginationLink . "</ul></nav>";
}
And in my Javascript file I have this:
$(document).ready(function(){
$('.pagination').pagination({
items: 50,
itemsOnPage: 10,
cssStyle: 'light-theme',
hrefTextPrefix: '?page=inbox_sent&list='
});
$( ".navlink" ).click(function() {
$(".navlink").removeClass('active');
$(this).addClass('active');
});
});
All results are displayed correctly, but active class of pagination always stays the same.
var paidamount = 500;
var amountpaid = 0;
var balance_amount = 0;
var list = [];
$("table tr").each(function() {
var $this = $(this);
var price = $this.find('td:nth-child(1)').text();
if (paidamount >= parseFloat(price)) {
paidamount -= parseFloat(price);
amountpaid = price;
balance_amount = 0;
} else {
amountpaid = 0;
balance_amount = price;
}
list.push({
price: price,
paid_amount: amountpaid,
balance: balance_amount
});
});
for (var i = 0; i < list.length; i++) {
$("table tbody").empty();
var tr = $('<tr/>');
tr.append("<td width=20>" + list[i].price + "</td>");
tr.append("<td width=140 >" + list[i].paid_amount + "</td>");
tr.append("<td width=140 >" + list[i].balance + "</td>");
$("table tbody").append(tr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td width="40" class="">300.00</td>
</tr>
<tr>
<td width="40" class="">190.00</td>
</tr>
<tr>
<td width="40" class="">150.00</td>
</tr>
<tr>
<td width="40" class="">150.00</td>
</tr>
<tr>
<td width="40" class="">150.00</td>
</tr>
<tr>
<td width="40" class="">150.00</td>
</tr>
</table>
At start I have 500 as starting price then I want to distribute it on each tr until it is down to zero.
Expected:
First row first column is price 300 then second column is should be 300 since 500 is enough to pay 300 then balance is 0 since 300 is full paid. next row is 190 for price then second should be 190 since 200 is enough to pay 190 then balance is zero since 190 is full paid. next row 150 second row is 10 since 10 is what is left from previous transaction then last column is 140 since 150 is not paid completely and only 10 is paid. Rest will have balance of price then not paid amount since the cash left is 0 .
I've updated your code to fix the issues. One of the fixes is to remove the $("table tbody").empty(); statement out of the for loop, you only need to run this once. If you keep it inside the for loop, it'll empty the table after each iteration and only the last row will be appended.
Secondly I simplified the logic inside the $("table tr").each() function. You should move all variables that are local to a particular row to be inside this function, logically it makes more sense, so you don't have to reset it after each iteration. The logic is simple, you set a tempAmount equal to the startingAmount(500) minus the price of the row. Then set amountPaid equal to price and balanceAmount equal to 0. Assume they have been fully paid. Then check to see that the tempAmount is still greater than 0, if so its correctly fully paid, otherwise you don't have enough to pay. In this case, just update the amountPaidto equal the the remaining amount , which at this point is startingAmount, and update balanceAmount to equal price minus startingAmount. Finally set the startingAmount to 0 so all future iterations will result in the else statement running.
var startingAmount = 500;
var list = [];
$("table tr").each(function() {
var $this = $(this);
var price = parseFloat($this.find('td:nth-child(1)').text());
var tempAmount = startingAmount - price;
var amountPaid = price;
var balanceAmount = 0;
if(tempAmount > 0){
startingAmount = tempAmount;
}else{
amountPaid = startingAmount;
balanceAmount = price - startingAmount;
startingAmount = 0;
}
list.push({
price: price,
paid_amount: amountPaid,
balance: balanceAmount
});
});
$("table tbody").empty();
for (var i = 0; i < list.length; i++) {
var tr = $('<tr/>');
tr.append("<td width=20>" + list[i].price + "</td>");
tr.append("<td width=140 >" + list[i].paid_amount + "</td>");
tr.append("<td width=140 >" + list[i].balance + "</td>");
$("table tbody").append(tr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td width="40" class="">300.00</td>
</tr>
<tr>
<td width="40" class="">190.00</td>
</tr>
<tr>
<td width="40" class="">150.00</td>
</tr>
<tr>
<td width="40" class="">150.00</td>
</tr>
<tr>
<td width="40" class="">150.00</td>
</tr>
<tr>
<td width="40" class="">150.00</td>
</tr>
</table>
hi i have a page of invoice where i can add rows using jquery. i am able to add plain text box from .js file but i want to add a drop down menu insted of textbox. justlike default row in php page.
my page code is
<?php
$con = mysql_connect("localhost","root","");
$db = mysql_select_db("inventory_erp",$con);
$getitem=mysql_query("SELECT * FROM 0_stock_master ORDER BY stock_id ASC");
$item = '';
while($row = mysql_fetch_assoc($getitem))
{
$item .= '<option value = "'.$row['id'].'">'.$row['stock_id'].'</option>';
}
$getdescription=mysql_query("SELECT * FROM 0_stock_master ");
$description = '';
while($row2 = mysql_fetch_assoc($getdescription))
{
$description .= '<option value = "'.$row2['description'].'">'.$row2['description'].'</option>';
}
?>
<!DOCTYPE html>
<!-- saved from url=(0047)http://css-tricks.com/examples/EditableInvoice/ -->
<html lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta charset="UTF-8">
<title>Editable Invoice</title>
<script src="./Editable Invoice_files/jquery-1.3.2.min.js"></script>
<script src="./Editable Invoice_files/example.js"></script>
</head>
</html>
<table id="items">
<tbody><tr>
<th>Item</th>
<th>Description</th>
<th>Unit Cost</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr class="item-row">
<td class="item-name"><div class="delete-wpr"><select name="age"> <?php echo $item; ?> </select><a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td class="description"><select name="age"> <?php echo $description; ?> </select></td>
<td><textarea class="cost">$0.00</textarea></td>
<td><textarea class="qty">1</textarea></td>
<td><span class="price">$0.00</span></td>
</tr>
<tr id="hiderow">
<td colspan="5"><a id="addrow" href="javascript:;" title="Add a row">Add a row</a></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Subtotal</td>
<td class="total-value"><div id="subtotal">$0.00</div></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Total</td>
<td class="total-value"><div id="total">$0.00</div></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line">Amount Paid</td>
<td class="total-value"><textarea id="paid">$0.00</textarea></td>
</tr>
<tr>
<td colspan="2" class="blank"> </td>
<td colspan="2" class="total-line balance">Balance Due</td>
<td class="total-value balance"><div class="due">$0.00</div></td>
</tr>
</tbody></table>
i am using a example.js file to add rows dynamically.
example.js
function print_today() {
// ***********************************************
// AUTHOR: WWW.CGISCRIPT.NET, LLC
// URL: http://www.cgiscript.net
// Use the script, just leave this message intact.
// Download your FREE CGI/Perl Scripts today!
// ( http://www.cgiscript.net/scripts.htm )
// ***********************************************
var now = new Date();
var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate();
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;
}
var today = months[now.getMonth()] + " " + date + ", " + (fourdigits(now.getYear()));
return today;
}
// from http://www.mediacollege.com/internet/javascript/number/round.html
function roundNumber(number,decimals) {
var newString;// The new rounded number
decimals = Number(decimals);
if (decimals < 1) {
newString = (Math.round(number)).toString();
} else {
var numString = number.toString();
if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
numString += ".";// give it one at the end
}
var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
if (d1 != ".") {
cutoff -= 1;
d1 = Number(numString.substring(cutoff,cutoff+1));
} else {
cutoff -= 1;
}
}
}
d1 += 1;
}
if (d1 == 10) {
numString = numString.substring(0, numString.lastIndexOf("."));
var roundedNum = Number(numString) + 1;
newString = roundedNum.toString() + '.';
} else {
newString = numString.substring(0,cutoff) + d1.toString();
}
}
if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
newString += ".";
}
var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
for(var i=0;i<decimals-decs;i++) newString += "0";
//var newNumber = Number(newString);// make it a number if you like
return newString; // Output the result to the form field (change for your purposes)
}
function update_total() {
var total = 0;
$('.price').each(function(i){
price = $(this).html().replace("$","");
if (!isNaN(price)) total += Number(price);
});
total = roundNumber(total,2);
$('#subtotal').html("$"+total);
$('#total').html("$"+total);
update_balance();
}
function update_balance() {
var due = $("#total").html().replace("$","") - $("#paid").val().replace("$","");
due = roundNumber(due,2);
$('.due').html("$"+due);
}
function update_price() {
var row = $(this).parents('.item-row');
var price = row.find('.cost').val().replace("$","") * row.find('.qty').val();
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("$"+price);
update_total();
}
function bind() {
$(".cost").blur(update_price);
$(".qty").blur(update_price);
}
$(document).ready(function() {
$('input').click(function(){
$(this).select();
});
$("#paid").blur(update_balance);
$("#addrow").click(function(){
$(".item-row:last").after('<tr class="item-row"><td class="item-name"><div class="delete-wpr"><select name="age"> <?php echo $option; ?> </select><a class="delete" href="javascript:;" title="Remove row">X</a></div></td><td class="description"><textarea>Description</textarea></td><td><textarea class="cost">$0</textarea></td><td><textarea class="qty">0</textarea></td><td><span class="price">$0</span></td></tr>');
if ($(".delete").length > 0) $(".delete").show();
bind();
});
bind();
$(".delete").live('click',function(){
$(this).parents('.item-row').remove();
update_total();
if ($(".delete").length < 2) $(".delete").hide();
});
$("#cancel-logo").click(function(){
$("#logo").removeClass('edit');
});
$("#delete-logo").click(function(){
$("#logo").remove();
});
$("#change-logo").click(function(){
$("#logo").addClass('edit');
$("#imageloc").val($("#image").attr('src'));
$("#image").select();
});
$("#save-logo").click(function(){
$("#image").attr('src',$("#imageloc").val());
$("#logo").removeClass('edit');
});
$("#date").val(print_today());
});
i am using this code in exampe.js file to add text box (Description) in new row. but i want a drop down menu from mysql database.
Let's say I have a dynamic table in php page.... is there a way I can export what I have from the dynamic table to a CSV file (and text file [if possible]) via PHP...
Here I am getting data from table and show it in alert box. But I want to save it in a file. Using php.
Here is my code:
<html>
<head>
<script>
function GetCellValues()
{
var str = '';
var rows = document.getElementsByTagName('tr');
var table=document.getElementById("project");
for (var i=0;i<table.rows[0].cells.length;i++)
{
if (i > 2 )
{
str = str + table.rows[0].cells[3].innerHTML.replace(", ");
}
else
{
str = str + (table.rows[0].cells[i].innerHTML) + ', ' ;
}
}
for (var c = 1 ; c < rows.length ; c++)
{
str += '\n' + "0" + c + ', ';
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
if (k > 1)
{
str += inputs[k].value.replace(", ");
}
else
{
str += inputs[k].value + ', ';
}
}
document.getElementById('hiden').value = str;
alert(document.getElementById('hiden').value);
}
</script>
</head>
<body>
<form>
<br>
<h1><u>PROJECT</u> :</h1>
<br>
<input type = "hidden" id = "hiden" name = "hiden" value = "">
<input type = "button" name = "submit" onclick = "GetCellValues()" Value = "SAVE">
<br>
</form>
<?php
$handle = fopen("data.csv", "w");
$hide = $_REQUEST['hide'];
fwrite($handle,$hide);
$file = file('data.csv');
$lines = count($file);
echo'<table id = "project" border = "1" cellpadding="2" cellspacing="0"
style = "width: 60%; margin-left: auto; margin-right: auto; border-color: brown; background-color:silver;">';
echo'<tr cellpadding="100">
<th width="15%">Sl.No.</th>
<th width="15%">Project Name</th>
<th width="15%">ChangeDate</th>
<th width="15%">Changed By</th>
</tr>';
for ($i=1; $i<$lines; $i++)
{
$part = explode(',', $file[$i]);
echo'<tr>
<td align= "center" width="5%">'.$part[0].'</td>
<td align= "center" width="25%"><input type="text" value='.$part[1].'></td>
<td align= "center" width="25%"><input type="text" value='.$part[2].'></td>
<td align= "center" width="25%"><input type="text" value='.$part[3].'></td>
</tr>';
}
echo'</table>';
?>
</body>
</html>
you could use the built in PHP5 function fputcsv
here is a sample code
$result = mysqli_query($con, 'SELECT * FROM table_name');
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$fp = fopen('file.csv', 'w');
foreach ($row as $val) {
fputcsv($fp, $val);
}
fclose($fp);
It will return a comma separated string for each row written to file.csv: