update the database without page refresh - php

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 */
?>

Related

How to display searching data on the same link of page on PHP by clicking a submit button?

enter image description here
Hi Guys, I have the following problem:
In the url
"/media.php?module=riwayat&noreg=00020517"
All data with 'noreg = 00020517' is displayed. I want to filter the displayed data with 'keyword' entered in the textbox after the 'cari' button is clicked. How to without change the url?
the code on 'riwayat.php' is:
switch($_GET[act]){
default:
$aksi="modul/riwayat/aksi_riwayat.php";
$table = 'pasien';
$noreg = $_GET[noreg];
$text = "SELECT * FROM $table WHERE noreg = $noreg";
$sql1 = mysql_query($text);
$row1 = mysql_num_rows($sql1);
echo "<div id='dalam_content'>
<h2>RIWAYAT PASIEN</h2>
<div id='info_pasien'>
";
if ($row1>0){
while ($r=mysql_fetch_array($sql1)){
$lahir =new DateTime($r['tgl_lahir']);
// Convert Ke Date Time
$today = new DateTime();
$umur = $today->diff($lahir);
echo "
<table>
<tr>
<td>NO REG.</b></td>
<td><b>: $r[noreg]</b></td>
</tr>
<tr>
<td>Nama</b></td>
<td><b>: $r[nama_pasien]</b></td>
</tr>
<tr>
<td>Tgl Lahir</b></td>
<td><b>: ".jin_date_str($r[tgl_lahir])."</b></td>
</tr>
<tr>
<td>Jenis Kelamin</b></td>
<td><b>: $r[kelamin]</b></td>
</tr>
<tr>
<td>Alamat</b></td>
<td><b>: $r[alamat]</b></td>
</tr>
<tr>
<td>UMUR</b></td>
<td><b>: "; echo $umur->y; echo " Tahun, "; echo $umur->m; echo " Bulan, dan "; echo $umur->d; echo " Hari"; echo "</b></td>
</tr>
</table>
</div>";
}}
echo"
<div id='tampil_data1'>
<div id='tombol-cari'>
<form method=POST action='$aksi?module=riwayat&act=cari' enctype='multipart/form-data'>
<input name=kata type=text size=23 maxlength=50 />
<input type=submit value=Cari>
<input type=hidden name=noreg value=$noreg>
</form>
<input type=button value='Pemeriksaan Baru' onclick=\"window.location.href='?module=riwayat&act=periksabaru&noreg=$noreg';\">
</div>
<table id='theTable' width='100%'>
<tr>
<th width='10%'>Tanggal</th>
<th>Pemeriksaan</th>
<th>Terapi</th>
</tr>";
$kata = trim($_POST['kata']);
$kata = htmlentities(htmlspecialchars($kata), ENT_QUOTES);
$table2 = 'riwayat';
$where3 = "WHERE noreg= $noreg AND pemeriksaan LIKE '%$kata%' OR terapi LIKE '%$kata%'";
$sql3 = "SELECT * FROM $table2 $where3 ORDER BY id ASC";
$query3 = mysql_query($sql3);
while($rows=mysql_fetch_array($query3)){
if ($kata==$kata){
$pemeriksaan=$rows[pemeriksaan];
$pemeriksaan = preg_replace( "/$kata/i", '<span style="background-color:yellow;">' . $kata . '</span>', $pemeriksaan );
$terapi=$rows[terapi];
$terapi = preg_replace( "/$kata/i", '<span style="background-color:yellow;">' . $kata . '</span>', $terapi );
}
else {
$pemeriksaan=$rows[pemeriksaan];
$terapi=$rows[terapi];
}
echo "
<tr>
<td align='center'>".jin_date_str($rows[tgl_periksa])."</td>
<td>$pemeriksaan</td>
<td>$terapi</td>
</tr>";
}
echo "
</table>";
break;
and the 'aksi_riwayat.php' code is:
$module=$_GET[module];
$act=$_GET[act];
$noreg= $_POST[noreg];
// Input pemeriksaanbaru
if ($module=='riwayat' AND $act=='input'){
mysql_query("INSERT INTO riwayat(tgl_periksa,
noreg,
pemeriksaan,
terapi)
VALUES('$_POST[tgl]',
'$_POST[noreg]',
'$_POST[pemeriksaan]',
'$_POST[terapi]')");
header('location:../../media.php?module=riwayat&noreg='.$noreg);
}
// Input Cari
elseif ($module=='riwayat' AND $act=='cari'){
header('location:../../media.php?module=riwayat&noreg='.$noreg);
}
You can use AJAX for this purpose.
After click on Submit button you have to pass data to server and get back response from server end. Once you get data you have to render on target position.
This link will give you better idea how you can integrate AJAX.
The following is sample code from the above link:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
If anymore doubt please let me know.

multiple submit on same page with php ajax

<div id="home">
<div class="container">
<form action="" method="post">
<b><font color = "000099"><select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select></font></b>
<b><font color = "000099"><select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select></b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /> </b>
<input type="submit" value="GO"/></font><br>
</form>
<font color = "339933"><b>
</b></font>
<p><div id="body">
<table width="98%" border="1">
<tr></tr>
<tr>
<td><font color = "339933"><b>Name</td>
<td><font color = "339933"><b>E-Mail </td>
<td><font color = "339933"><b>Access</td>
<td><font color = "339933"><b>Update </td>
</tr>
<?php
$read = $_POST['read'];
If($read == 'New'){
$read = '0';
}
If($read == 'Archive'){
$read = '1';
$arc = 'AND date < CURDATE() - INTERVAL 90 DAY';
}
$category = $_POST['category'];
$value = $_POST['value'];
if($category == 'Name'){
$where = " where name like '%$value%' ";
}else if($category == 'E-mail'){
$where = " where Email like '%$value%' ";
}else if($category == 'Employee'){
$where = " where Email like '%$value%' ";
}else if($category == 'Customer'){
$where = " where Email not like '%$value%' ";
}
$select = 'SELECT *';
$from = ' FROM users';
if($where == ''){
$where = ' WHERE TRUE ';
}
$order = " order by id desc limit 100";
if($read == '0'){
$sql = $select . $from . $where . $order ;
}else{
$sql = $select . $from . $where . $arc . $order ;
}
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set)) {
?>
<tr>
<form method="post" name="forms" action="">
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access']; ?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</form>
<?php } ?>
</table>
</div>
</body>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
alert('asfsfsds');
var ID = $(this).attr("id");
var dataString1 = 'msg_id='+ ID;
var mail = $("#remail").val();
var mailid = 'remail='+ mail;
var textcontent = $("#access_rights").val();
var dataString = 'access_rights='+ textcontent;
if(textcontent==''){
alert("Enter some Value..");
$("#access_rights").focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: dataString,mailid,dataString1,
cache: true,
success: function(html){
document.getElementById('access_rights').value='';
$("#access_rights").focus();
}
});
}
return false;
});
});
</script>
</html>
Above is my php ajax code. I want to one field in mysql database by ajax.
There are multiple submit button on the page. Let me explain you properly.
Below code is used for sorting the value on the page. This value retrieve from database. This is working fine. I can get the data from database and it is showing in the same page.
<form action="" method="post">
<b><font color = "000099">
<select name="category" id="category">
<option>Name </option>
<option>Email</option>
<option>Employee</option>
<option>Customer</option>
</select>
</font></b>
<b><font color = "000099">
<select name="read" id="read">
<option>New</option>
<option>Archive</option>
</select>
</b>
<font color = "339933"><b><input name="value" type="text" placeholder="Value" /></b>
<input type="submit" value="GO"/></font><br>
</form>
In below code data is showing from database and one text box and submit button will display in table.
<form method="post" name="forms" action="">
<tr>
<td><font color = Black><?php echo $row['name']; ?></td>
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
<td><input type="text" name="access_rights" class="form-control" value="<?php echo $row['access'];?>" required="required" ></td>
<td><input type="submit" class="submit_button" id="submit_button" name="submit_button" value="Update"/></td>
</tr>
</form>
I want user with special permission can update the value by ajax because there could be multiple rows and it is not good to page get refreshed each time.
At the moment after clicking on update button ajax event not firing.
Can anybody advise me on this. I am not good in ajax.
There may be other issues, but the following line is syntactically incorrect:
data: dataString,mailid,dataString1,
That is not how you concatenate a string in Javascript. Plus, you would need to separate the name=value pairs with ampersands.
Instead of concatenating a string, you can use an object and let JQuery do the concatenating:
data: {
'access_rights': $("#access_rights").val(),
'remail': $("#remail").val(),
'msg_id': $(this).attr("id")
},
UPDATE:
You don't have an element with id="access_rights. You do have an element with id="remail", but you create that element in a loop, so you will have multiple elements with that id.
You need to get the values of the elements that are in the same row as the clicked submit button. You can't do that using id values. Instead, you use .closest('tr') on the button element to get the surrounding row. You can then use .find() on the row element to get the values in that row.
Change:
<td><div id= "remail" name="remail"><font color = Black><?php echo $row['Email']; ?></div></td>
To:
<td><font color="Black" class="remail"><?php echo $row['Email']; ?></td>
Then you can have:
$(".submit_button").click(function() {
var $submitBtn = $(this),
$row = $(this).closest('tr'),
$accessRights = $row.find("input[name=access_rights]"),
accessRights = $accessRights.val();
if (accessRights == ''){
alert("Enter some Value..");
$accessRights.focus();
} else {
$.ajax({
type: "POST",
url: "action.php",
data: {
'access_rights': accessRights,
'remail': $row.find(".remail").text(),
'msg_id': $submitBtn.attr("id")
},
cache: true,
success: function(html){
$accessRights.val('').focus();
}
});
}
return false;
});
You are also missing the closing </tr> tag.

Dynamic dropdown list

subjects
course
chapters
I want to add 2 dynamic dropdown lists, one is for subjects, and one is for course. When I select subject, courses which is added to that subject should be loaded in the course dropdown list, and then add chapters to that courses.
How do I do that?
Any help would be appreciated.
Here is my code:
<div class="content-form-inner">
<div id="page-heading">Enter the details</div>
<div class="form_loader" id="thisFormLoader"></div>
<div id="error_message"></div>
<form name="thisForm" id="thisForm" action="editchapters.php?mode=<?php echo $_REQUEST['mode']; ?>&id=<?php echo $id; ?>" method="post" enctype="multipart/form-data">
<table border="0" cellpadding="0" cellspacing="0" id="id-form" >
<tr>
<th valign="top" style="width:0%"><span class="required">*</span>Subject</th>
<td style="width: 0%">
<select name="subject_name" class="select-form required " style="color:#000 !important;width:200px !important">
<option value="">Select</option>
<?php
$sql = "select * from mock_subject ";
$res = mysqli_query($dbhandle,$sql);
$numrows =mysqli_num_rows($res);
echo mysql_error();
if($numrows){
while($obj = mysqli_fetch_object($res)){
if($obj->status == 1){
if($subject == $obj->id){
echo '<option value="'.$obj->id.'" selected>'.($obj->subject_name).'</option>';
}
else{
echo '<option value="'.$obj->id.'">'.($obj->subject_name).'</option>';
}
}
}
}
?>
</select>
</td>
<td style="width: 0%;">
<div id="subject_id-error" class="error-inner"></div>
</td>
<td></td>
</tr>
<tr>
<th valign="top" style="width:0%"><span class="required">*</span>Course</th>
<td style="width: 0%">
<select name="course_name" class="select-form required " style="color:#000 !important;width:200px !important">
<option value="">Select</option>
<?php
$sql = "select * from mock_course ";
$res = mysqli_query($dbhandle,$sql);
$numrows =mysqli_num_rows($res);
echo mysql_error();
if($numrows){
while($obj = mysqli_fetch_object($res)){
if($obj->status == 1){
if($course == $obj->id){
echo '<option value="'.$obj->id.'" selected>'.($obj->course_name).'</option>';
}
else{
echo '<option value="'.$obj->id.'">'.($obj->course_name).'</option>';
}
}
}
}
?>
</select>
</td>
<td style="width: 0%;">
<div id="course_id-error" class="error-inner"></div>
</td>
<td></td>
</tr>
<tr>
<th><span class="required">*</span>Chapter</th>
<td><input type="text" name="chapter_name" class="inp-form required" value="<?php echo $chapter;?>" style="color:#000 !important;"></td>
<td>
<div></div>
</td>
</tr>
<tr>
<th> </th>
<td valign="top"><input type="submit" name="submit_button" value="<?php echo $mode=="edit"? "Update" : "Add" ?>" class="form-submit" />
<input type="reset" value="Reset" class="form-reset" />
</tr>
</table>
</form>
<div class="clear"></div>
</div>
One possible solution would, if your data set is comparatively small. Load all the data on page load, and use jquery to get value of dropdown, and based on that formulate the values for the other drop downs.
Second Solution would be to us AJAX and call data from your database for every action. and print using Angular.
I've attached a sample code for that.
This is my_script.js
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$(document).ready(function(){
callSetTimeout();
});
function callSetTimeout(){
setTimeout(function(){
update();
callSetTimeout();
},200);
}
function update(){
$http.get("http://localhost/WhatsOnYourMInd/db.php")
.success(function (response) {$scope.names = response.records;});
}
});
This is for db.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mind";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM data";
$result = $conn->query($sql);
$jsonString=array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($jsonString,array('id' =>$row['id'],'name' =>$row['name'],'message' =>$row['message']));
}
echo json_encode(array("records"=>$jsonString));
} else {
echo "0 results";
}
$conn->close();
?>
This is for index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Whats on your Mind</title>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<ul id="ajax"></ul>
<div ng-app="myApp" ng-controller="customersCtrl">
<ol>
<li ng-repeat="x in names">
{{ 'Id:'+x.id + ' Name:' + x.name +' Message:'+x.message}}
</li>
</ol>
</div>
<script src="my_script.js"></script>
</body>
</html>
Easiest way of creating dynamic dropdown is by using jquery inside the head tag.
Give onchange() event and guide the data to another page using jquery code, and then link 2 dropdowns. The code I did is like this, which I felt is the easiest way for dynamic dropdowns.
jquery which I included is
<script>
function ajaxDrp(data){
$.ajax({
method: "POST",
url: "chapterDropdown.php",
data: {
id: data
}
}).success(function(data) {
$('#selectCourse').empty();
$('#selectCourse').append(data);
});
}
</script>
#selectCourse is the id I have given to the other dropdown which have to be in sync with the first dropdown.
The given url in the jquery is the path where data of first dropdown is getting collected. In my case, the code is like this:
<?php
$id = $_REQUEST['id'];
$query = "SELECT * FROM `your table name` WHERE subject_id = " . $id;
$result = mysqli_query($dbhandle,$query);
$count = 0;
$option`enter code here` = '';
while($row = mysqli_fetch_assoc($result)) {
$option .= '<option
value="'.$row['id'].'">'.$row['course_name'].'</option>';
}
echo $option;
?>

Cannot delete row using check box

I'm trying to delete a row from table which is connected to database using checkbox (and it wouldn't matter if its just one row or multiple rows), but it is not working, as in nothing happens. It doesn't delete, no errors or warnings appear just a refresh.
php:
<?php
if(isset($_POST['del_event']))
{
if(isset($_POST['check']) && count($_POST['check']))
{
$array = array("check" => $_POST['check']);
$id = implode(',', $array['check']);
$result = mysql_query("DELETE FROM event WHERE event_id = '$id'") or die(mysql_error());
}
}
?>
html:
<form class="buttons" method="post" action="event.php">
<div class="button-wrap">
<input type="button" id="add_event" name="add_event" value="Add Event"/>
<input type="submit" id="del_event" name="del_event" value="Delete Event"/>
</div>
</form>
<tbody class="tbody-event-list-table2">
<?php
require "connection.php";
$check = mysql_query("SELECT * FROM event") or die(mysql_error());
if(mysql_num_rows($check) > 0)
{
while($row = mysql_fetch_array($check))
{
$id = $row['event_id'];
$name = $row['event_name'];
$start = $row['start'];
$end = $row['end'];
$venue = $row['event_venue'];
echo
"<tr>
<td><input type='checkbox' name='check' id='check' class='check' value='$id'/><a href=''
class='event-link'>$name</a></td><td>$start</td><td>$end</td><td>$venue</td>";
echo "</tr>";
}
}
else
{
echo
"<tr>
<td colspan='4'>There Are No Events.</td>
</tr>";
}
?>
</tbody>
It is if(isset($_POST['del_event'])) because 'del_event' is a name of a delete button which is disabled unless a checkbox is checked.
<script>
var chkbox = $(".check"),
button = $("#del_event");
button.attr("disabled","disabled");
chkbox.change(function(){
if(this.checked){
button.removeAttr("disabled");
}else{
button.attr("disabled","disabled");
}
});
</script>
php version is 5.5.9
This would still give you an undefined error if it is the check variable
if (isset($_POST['check']) && count($_POST['check']) != 0)
but if a checkbox is off in a form it is not sent with the form so it does not exist.
Carpetsmoker was halfway right, a proper solution would be:
if (isset($_POST['check'])) {
if ( (int) $_POST['check'] !== 0) {
}
}
btw, it is better to always cast your variables to a propert type you are checking for.
In PHP 0 can be 0, false or null.
Prevent this by safe type checking with the ===
so i fixed the prob. first i had to remove "form" that was separating the buttons and the table so now "form" is wrapped around both buttons and table. second is the php coding for deletion has changed too.
<form class="buttons" method="post" action="event.php">
<div class="button-wrap">
<input type="button" id="add_event" name="add_event" value="Add Event"/>
<input type="submit" id="del_event" name="del_event" value="Delete Event"/>
<input type="submit" id="edit_event" name="edit_event" value="Edit Event">
</div>
<div class="event-list-table2" >
<table class="event-table">
<thead>
<tr>
<th>Event Name</th>
<th>Start Event</th>
<th>End Event</th>
<th>Venue</th>
</tr>
</thead>
<tbody class="tbody-event-list-table2">
<?php
require "connection.php";
$check = mysql_query("SELECT * FROM event") or die(mysql_error());
if(mysql_num_rows($check) > 0)
{
while($row = mysql_fetch_array($check))
{
$id = $row['event_id'];
$name = $row['event_name'];
$start = $row['start'];
$end = $row['end'];
$venue = $row['event_venue'];
echo
"<tr>
<td><input type='checkbox' name='check[]' class='check' value='$id'><a href='' class='event-link' value='$id' name='event-link'>$name</a></td><td>$start</td><td>$end</td><td>$venue</td>";
echo "</tr>";
}
}
else
{
echo
"<tr>
<td colspan='4'>There Are No Events.</td>
</tr>";
}
?>
</tbody>
<?php
if (isset($_POST['del_event']) && isset($_POST['check']))
{
foreach($_POST['check'] as $del_id)
{
$del_id = (int)$del_id;
$sql = mysql_query("DELETE FROM event WHERE event_id = $del_id") or die(mysql_error());
if($sql)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=event.php\">";
}
}
}
?>
</table>
</div>
</form>

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

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>

Categories