How to auto-sum column and save to MySQL database? - php

How can I auto-sum the "Total Hours" data in the tfoot and save to MySQL database and re-display in same area? I've got two examples working, I would like to add the auto-sum functionality to the VizaHours web-app.
Working examples are here:
http://onetimemobile.com/vizahours/index.php
http://onetimemobile.com/autosummer
EDITED 4-2-14 ADDED ALL CODE index.php below:
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<table>
<thead>
<tr>
<th> DAY </th>
<th> DAY INFO </th>
<th> HOURS </th>
</tr>
<tfoot>
<tr id="summation">
<td class="total-hours" colspan="2">TOTAL HRS >>>>></td>
<td><span>0</span></td>
</tr>
<tr>
<th colspan="3">BUD HOURS - START WEEK 3-24-14<br />unpaid</th>
</tr>
</tfoot>
</thead>
<tbody>
<?php
include('connect.php');
$result = $db->prepare("SELECT * FROM budsvizahours ORDER BY id DESC");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<tr class="record">
<td><?php echo $row['fname']; ?><br /><br /><a href="editform.php?id=<?php echo
$row['id']; ?>"> Edit </a></td>
<td><?php echo $row['lname']; ?></td>
<td><?php echo $row['age']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</body>
</html>
EDITED 4-2-14 ADDED ALL CODE edit.php below:
<?php
// configuration
include('connect.php');
// new data
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$age = $_POST['age'];
$id = $_POST['memids'];
// query
$sql = "UPDATE budsvizahours
SET fname=?, lname=?, age=?
WHERE id=?";
$q = $db->prepare($sql);
$q->execute(array($fname,$lname,$age,$id));
header("location: index.php");
?>
EDITED 4-2-14 ADDED ALL CODE editform.php below:
<?php
include('connect.php');
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM budsvizahours WHERE id= :userid");
$result->bindParam(':userid', $id);
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<form action="edit.php" method="POST">
<input type="hidden" name="memids" value="<?php echo $id; ?>" />
<br>
<input type="hidden" name="fname" value="<?php echo $row['fname']; ?>" /><br>
Update Day Info<br>
<input type="text" name="lname" value="<?php echo $row['lname']; ?>" /><br>
Hours This Day<br>
<input class="record" type="tel" name="age" value="<?php echo $row['age']; ?>" />
<br><br>
<button class="edit-info-button" type="submit" value="Save">Save</button>
</form>
<?php
}
?>
<script>
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value); }
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
</body>
</html>

//it work for your code...
//sum query is good but i case you don't want to do it by that way
<script type="text/javascript">
$(document).ready(function() {
var sum = cls_nm_tr = 0;//create variable to null or zero
//making loop for your tr its depends on no of tr you have
$('.record').each(function(i,e){
var cls_nm_tr = $('td:eq(2)', this).html();//getting value from td
sum = parseInt(sum) + parseInt(cls_nm_tr);//adding them in sum varible
});//loops ends here
console.log(sum);//here you got sum of HOURS.//"sum" variable have sum or hours
//$(".yoru_footer_id").html(sum);//here you can put data in tfooter
});
</script>

Related

Using a button to move to the next record

I would like to move to the next record using an HTML button. I have tried for and foreach SQL statements I have also tried using num rows and calling the cells values.
$id=$_get['Badge ID Number'];
$sqlkc = "select * from Badges.BADGEMSTR";
$result = mysqli_query($sqlc, $sqlkc);
if($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$BIDN= $row['Badge ID Number'];
$Fname= $row['First Name'];
$MI= $row['Middle Initial'];
$Lname= $row['Last Name'];
}
$next = next($result);
?>
Thank you in advance for your help.
Forgot to add my current onclick command
onclick='<?php echo $next;?>'
All HTML code as requested
<table style="background-color: tan; margin: auto">
<tr>
<td><input type="text" value="<?php echo $BIDN;?>"/>
<input type="text" value="01"/></td>
</tr>
<tr>
<td>
<input type="text" value="<?php echo $Fname;?>"/>
<input type="text" value="<?php echo $MI;?>"/>
<input type="text" value="<?php echo $Lname;?>"/>
</td>
</tr>
<tr>
<td><input type="button" value="Next" style="float: right" onclick='<?php echo $next;?>'/></td>
<td><input type="button" value="Last" style="float: right" onclick='<?php echo $nextid;?>'/></td>
</tr>
</table>
I hope I understood the question right.
Since you would pass the Badge ID between pages, you should use prepared statements as such. So, taking the Badge ID Number is Integer, your PHP code should look like this:
$link = mysqli_connect(hostname,username,password,dbname);
if (isset($_GET['last_id'])) {
// Last row in the table
$stmt = mysqli_prepare($link, 'SELECT * FROM Badges.BADGEMSTR ORDER BY `Badge ID Number` DESC LIMIT 1');
} elseif (isset($_GET['id'])) {
// Specific row in the table
$stmt = mysqli_prepare($link, 'SELECT * FROM Badges.BADGEMSTR WHERE `Badge ID Number`>? ORDER BY Rb ASC LIMIT 1');
$stmt->bind_param('d',$_GET['id']);
} else {
// First row in the table
$stmt = mysqli_prepare($link, 'SELECT * FROM Badges.BADGEMSTR ORDER BY `Badge ID Number` ASC LIMIT 1');
}
// Execute the query and get the results
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_array();
// Initialize variables from the given $row
$BIDN = $row['Badge ID Number'];
$Fname = $row['First Name'];
$MI = $row['Middle Initial'];
$Lname = $row['Last Name'];
As for the HTML code, it's a bit unclear from the question, but I think something like this would be in order:
<html>
<head></head>
<body>
<table style="background-color: tan; margin: auto">
<tr>
<td><?php echo htmlspecialchars($BIDN, ENT_QUOTES); ?></td>
<td>01</td>
</tr>
<tr>
<td><?php echo htmlspecialchars($Fname, ENT_QUOTES); ?></td>
<td><?php echo htmlspecialchars($MI, ENT_QUOTES); ?></td>
<td><?php echo htmlspecialchars($Lname, ENT_QUOTES); ?></td>
</tr>
<tr>
<td>
Next
</td>
<td>
Last
</td>
</tr>
</table>
</body>
</html>
You also don't have to use inputs to display the results, you could show them between TD elements in the table like <td><?php echo $row['Badge ID Number']; ?>.

Submit buttons render under table data. I want only one submit button for the form

My problem is a submit button renders under each row of table data. I have searched all over the web to find out, how I can code to use only one submit for the entire form. As it is I can only submit $_POST for one row whereas I need to submit the entire form for processing.
Here is my Code:
<?php
require("config.inc.php");
session_start();
$usrname = $_POST["uname"]; //variable passed from validateuser.html
global $usrname;
//echo $usrname;
// initial query
$query = "SELECT * FROM dfd_usr_profiles WHERE username= '".$usrname."'";
/*$query2 = "UPDATE dfd_usr_profiles SET filters = :fltrs,
regions = :regns
WHERE $usrname = :username"; */
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Profile Information Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["userID"] = $row["userID"];
$post["username"] = $row["username"];
$post["filters"] = $row["filters"];
$post["regions"] = $row["regions"];
//update our repsonse JSON data
array_push($response["posts"], $post);
$endi = count($post);
//echo $endi;
?>
<!DOCTYPE html>
<html>
<script type="text/javascript">
function getRow(n) {
var row = n.parentNode.parentNode;
var cols = row.getElementsByTagName("td");
var i=0;
while (i < cols.length) {
alert(cols[i].textContent);
i++;
}
}
</script>
<body>
<form name="updatefilters" action="update_action.php" method="post" enctype="multipart/form-data>" id="update">
<!-- <input type="submit" name="submit" id="update" value="Update" /> -->
<fieldset>
<table border="1" >
<legend>Update Filters and Regions</legend>
<tr>
<td><input type="checkbox" name="pID[]" value="<?php echo $post['userID']; ?>" onclick="getRow(this)" /></td>
<td><input type="input" name="uname" value="<?php echo $usrname;?>" /></td>
<td><?php echo $post['filters']; ?></td>
<td><label valign="top" for="" id="mfiltervals">Select Deal Type(s) you want:</label></p></td>
<td><?php require("dtypelist.php");?></td>
<td><?php echo $post['regions']; ?></td>
<td><label valign="top" for="" id="mregionvals">Select Region(s) you want:</label></td>
<td><?php require("regionslist.php");?></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
<?php
echo '<button type="submit" name="submitupdate" form="update">Update</button>';
}
// echoing JSON response
// echo json_encode($response); // Commented out: Displays profile unformatted data. TC 070516.
} else {
$response["success"] = 0;
$response["message"] = "No information for this Username is available!";
die(json_encode($response));
}
// session_start(); place-holder
?>
Please help.
You need to move the foreach and the submit button that you have in the code below. All the other code is not relevant for this change. I have marked the 3 parts that need to be moved with // **** Move:
// **** Move this block to just before the `<tr>` tag
foreach ($rows as $row) {
$post = array();
$post["userID"] = $row["userID"];
$post["username"] = $row["username"];
$post["filters"] = $row["filters"];
$post["regions"] = $row["regions"];
//update our repsonse JSON data
array_push($response["posts"], $post);
$endi = count($post);
//echo $endi;
?>
<!DOCTYPE html>
<html>
<script type="text/javascript">
function getRow(n) {
var row = n.parentNode.parentNode;
var cols = row.getElementsByTagName("td");
var i=0;
while (i < cols.length) {
alert(cols[i].textContent);
i++;
}
}
</script>
<body>
<form name="updatefilters" action="update_action.php" method="post" enctype="multipart/form-data>" id="update">
<!-- <input type="submit" name="submit" id="update" value="Update" /> -->
<fieldset>
<table border="1" >
<legend>Update Filters and Regions</legend>
<tr>
<td><input type="checkbox" name="pID[]" value="<?php echo $post['userID']; ?>" onclick="getRow(this)" /></td>
<td><input type="input" name="uname" value="<?php echo $usrname;?>" /></td>
<td><?php echo $post['filters']; ?></td>
<td><label valign="top" for="" id="mfiltervals">Select Deal Type(s) you want:</label></p></td>
<td><?php require("dtypelist.php");?></td>
<td><?php echo $post['regions']; ?></td>
<td><label valign="top" for="" id="mregionvals">Select Region(s) you want:</label></td>
<td><?php require("regionslist.php");?></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
<?php // **** Move this up to just after the `</table>` tag
echo '<button type="submit" name="submitupdate" form="update">Update</button>';
// **** Move this closing brace just after the `</tr>` tag
}
After the 3 moves, it looks as follows -- see comments with ****MOVED****:
?>
<!DOCTYPE html>
<html>
<script type="text/javascript">
function getRow(n) {
var row = n.parentNode.parentNode;
var cols = row.getElementsByTagName("td");
var i=0;
while (i < cols.length) {
alert(cols[i].textContent);
i++;
}
}
</script>
<body>
<form name="updatefilters" action="update_action.php" method="post" enctype="multipart/form-data>" id="update">
<!-- <input type="submit" name="submit" id="update" value="Update" /> -->
<fieldset>
<table border="1" >
<legend>Update Filters and Regions</legend>
<?php // ****MOVED****
foreach ($rows as $row) {
$post = array();
$post["userID"] = $row["userID"];
$post["username"] = $row["username"];
$post["filters"] = $row["filters"];
$post["regions"] = $row["regions"];
//update our repsonse JSON data
array_push($response["posts"], $post);
$endi = count($post);
//echo $endi;
?>
<tr>
<td><input type="checkbox" name="pID[]" value="<?php echo $post['userID']; ?>" onclick="getRow(this)" /></td>
<td><input type="input" name="uname" value="<?php echo $usrname;?>" /></td>
<td><?php echo $post['filters']; ?></td>
<td><label valign="top" for="" id="mfiltervals">Select Deal Type(s) you want:</label></p></td>
<td><?php require("dtypelist.php");?></td>
<td><?php echo $post['regions']; ?></td>
<td><label valign="top" for="" id="mregionvals">Select Region(s) you want:</label></td>
<td><?php require("regionslist.php");?></td>
</tr>
<?php // ****MOVED****
}
?>
</table>
<?php // ****MOVED****
echo '<button type="submit" name="submitupdate" form="update">Update</button>';
?>
</fieldset>
</form>
</body>
</html>
<?php
Make sure to add <?php and ?> where necessary to switch correctly between PHP and normal output.

update the database without page refresh

Whenever the hyperlink with the yes id is clicked i dont want the page to refresh and then show the status, i want the status to change instant without page refreshing. I know Ajax deals with this, but can anyone provide me with a working example with my code please? As it melting my head :/
<h3 class="page-header"> Enquiries </h3>
<form id="enquiry" method="post" action="enquiry_csv.php">
<table class="table table-bordered table-hover">
<thead>
<tr>
<th> First Name</th>
<th> Last Name</th>
<th>Email</th>
<th>Message</th>
<th>Date</th>
<th>Responded to Enquiry?</th>
<th>Status</th>
<th></th>
<th><input class='btn-success' name='export' id='btnExport' type='submit' value='Export to CSV'/></th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * FROM enquiries";
$select_enquiries = mysqli_query($connection,$query);
while($row = mysqli_fetch_assoc($select_enquiries)) {
$Enquiry_ID = $row['Enquiry_ID'];
$FirstName = $row['First_Name'];
$LastName =$row['Last_Name'];
$Email = $row['Email'];
$Message = $row['Message'];
$Date =$row['Date'];
$Responded =$row['Responded'];
echo "<tr>";
echo "<td>$FirstName </td>";
echo "<td>$LastName </td>";
echo "<td>$Email </td>";
echo "<td>$Message </td>";
echo "<td>$Date </td>";
echo "<td> <a id='yes' class='success' style='' href='enquiries.php?Yes=$Enquiry_ID'>Yes</a> | <a class='success' href='enquiries.php?No=$Enquiry_ID'>No</a> </td>";
echo "<td> $Responded</td>";
echo "<td> <a class='btn btn-danger' href ='enquiries.php?delete=$Enquiry_ID'>Delete</a> </td>";
echo "</tr>";
}
?>
<?php
if(isset($_GET['Yes'])){
$enquiry_id = $_GET['Yes'];
$query = "UPDATE enquiries SET Responded = 'Yes' WHERE Enquiry_ID = {$Enquiry_ID}";
$query = mysqli_query($connection, $query);
}
if(isset($_GET['No'])){
$enquiry_id = $_GET['No'];
$query = "UPDATE enquiries SET Responded = 'No' WHERE Enquiry_ID = {$Enquiry_ID}";
$query = mysqli_query($connection, $query);
}
if(isset($_GET['delete'])){
$review_id = $_GET['delete'];
$query = "DELETE FROM enquiries WHERE Enquiry_ID = {$Enquiry_ID} ";
$delete_query = mysqli_query($connection, $query);
}
?>
<tr>
<td></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
</form>
You can do it with jquery ajax api it performs an asynchronous HTTP (Ajax) request
http://api.jquery.com/jquery.ajax/
Refer the above link which #Sanya Zahid posted and try to do some thing like this:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var age = $("#age").val();
var dataString = 'name='+ name +'&age='+ age;
if(name=='' || age =='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<form method="post" name="form">
<input id="name" name="name" type="text" /><br>
<input id="age" name="age" type="text"/>
<div>
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Data</span>
<span class="success" style="display:none"> Data Saved!!</span>
</div>
</form>
Here submit.php contains database related stuff(insert/update/delete). I just added name and age fileds here in code. Add fields as per your form.
submit.php :
<?php
$conn = mysqli_connect("localhost","root","","test");
/* Insert form data with out page refresh */
if($_POST)
{
$name=$_POST['name'];
$age = $_POST['age'];
mysqli_query($conn,"Query will come here");
}else{
echo "Please try again!!";
}
/* Insert form data with out page refresh */
?>

Query Data From Database Using Date Range in PHP/MySQL

I am new here is the script index.php of query data from database using date range in PHP/MySQL.
<link rel="stylesheet" type="text/css" href="tcal.css" />
<script type="text/javascript" src="tcal.js"></script>
<form action="index.php" method="get">
From : <input type="text" name="d1" class="tcal" value="" /> To: <input type="text" name="d2" class="tcal" value="" /> <input type="submit" value="Search">
</form>
<table id="resultTable" data-responsive="table" style="text-align: left; width: 400px;" border="1" cellspacing="0" cellpadding="4">
<thead>
<tr>
<th> Birtday </th>
<th> Name </th>
<th> Gender </th>
</tr>
</thead>
<tbody>
<?php
include('connect.php');
if (isset($_GET["d1"])) { $d1 = $_GET["d1"]; } else { $d1=0; };
if (isset($_GET["d2"])) { $d2 = $_GET["d2"]; } else { $d2=0; };
$result = $db->prepare("SELECT * FROM birthday WHERE date BETWEEN :a AND :b");
$result->bindParam(':a', $d1);
$result->bindParam(':b', $d2);
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
?>
<tr class="record">
<td><?php echo $row['date']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['gender']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
Now in this script we have 2 calenders for using the date range... Some one here who edit this script make into only 1 calender for selecting date.
PHP stores dates in the format "YYYY-MM-DD". I presume that the input for calendar would return date in the above format.
Rest of the code looks pretty good to me but you need to change this
{ $d1=0; };
To
{ $d1="0000-00-00"; };
If you remove references to d2 and change the query to this, it should work:
$result = $db->prepare("SELECT * FROM birthday WHERE date = :a ");

Records not getting inserted in ascending order

I'm having a strange problem. I have a HTML page with PHP code which inserts data to a MySQL database. The data gets saved to the DB without any errors but in an incorrect order.
Here's a screenshot. The table on the right side displays the existing records. The first 2 records are shown correctly.
But when I save more records, it displays like this.
Even in the MySQL table, the records are inserted that way.
I'm not sure where exactly the problem is so I've shown the whole code for the page below. I've commented what each code block does. Please comment if you need me to clarify something.
The Location ID is an auto-generated code.
<html>
<head>
<script language="javascript">
function SelectAll(source)
{ //The code for the 'Select All' checkbox
checkboxes = document.getElementsByTagName("input");
for(var i in checkboxes)
{
if(checkboxes[i].type == 'checkbox')
{
checkboxes[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<?php
//Database connection initialization
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new Location ID */
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row['LID'];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
//$id_num = sprintf("%03d", $id_num);
$new_id = $id_letter . $id_num;
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<! The table which displays the existing records >
<div id="display">
<b>Locations</b><br/><br/>
<form name="displayLocs" action="<?php echo $PHP_SELF; ?>" method="post" >
<table border="1">
<tr>
<th>Location ID</th>
<th>Code</th>
<th>Location</th>
<th><i>Delete</i></th>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><? echo $row["LID"]; ?></td>
<td align="center"><? echo $row["Code"]; ?></td>
<td><? echo $row["Location"]; ?></td>
<td align="center"><input type="checkbox" name="checkbox[]" value="<? echo $row["LID"]; ?>" /></td>
</tr>
<?php
}
?>
</table>
<br/>
<div id="buttons2">
<input type="checkbox" onclick="SelectAll(this)" />Select All <input type="reset" value="Clear" /> <input type="submit" value="Delete" name="deletebtn" />
</div>
</form>
</div>
<! New record saving area >
<b id="loc_caption_1">Enter a new location</b>
<div id="loca">
<form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Location ID</td>
<td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" name="code" style="text-align:right" /></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="loc" style="text-align:right" /></td>
</tr>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</div>
</form>
<?php
//Saving record
if(isset($_POST["savebtn"]))
{
$id = $_POST["lid"];
$code = $_POST["code"];
$location = $_POST["loc"];
$query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";
$result = mysql_query($query, $conn);
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<br/><br/>";
echo "<strong>1 record added successfully!</strong>";
echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">";
}
mysql_close($conn);
}
//Deleting selected records
if(isset($_POST["deletebtn"]))
{
for($i = 0; $i < $count; $i++)
{
$del_id = $_POST["checkbox"][$i];
$query = "DELETE FROM locations WHERE LID = '$del_id' ";
$result = mysql_query($query, $conn);
}
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=locations.php\">";
}
mysql_close($conn);
}
?>
</body>
</html>
Can anyone please tell me what is causing this and how to rectify it.
Thank you.
The records in the database are stored in the database in no particular order (well, there's some order to it, but it's up to the engine to determine it). If you want to get the results in a particular order, then you need to explicitly specify it when querying the data. In your case, make this change:
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations ORDER BY lid";
$result = mysql_query($query, $conn);

Categories