calculate value of selected checkboxes - php

I have a PHP page displaying the results of a MySQL query. It adds checkboxes to each row. The selected rows are then inserted into another table on submit.
My application is a Transport planning platform. I am looking for a way to display the total weight of the selected rows in real time, a box at the top of the page dispalying the current sum of the selected rows.
Can anybody guide me on how to add this functionality to my existing page.
My code currently is shown below:
<?php
mysql_connect("localhost", "username", "password")or die("cannot connect");
mysql_select_db("databasename")or die("cannot select DB");
$sql="SELECT `crtd dept`,`customer`,`case no`,`gross mass` from despgoods_alldetails where transporttypename= 'localpmb'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<table border=1>
<tr>
<td>
<form name="form1" method="post">
<table>
<tr>
<td>#</td>
<td>Dispatch Area</td>
<td>Customer</td>
<td>Case Number</td>
<td>Weight</td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><input type="checkbox" name=check[] value="<?php echo $rows['case no']; ?>"></td>
<td><?php echo $rows['crtd dept']; ?></td>
<td><?php echo $rows['customer']; ?></td>
<td><?php echo $rows['case no']; ?></td>
<td><?php echo $rows['gross mass']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan=3><input name="Next" type="submit" id="Next" value="Next"></td>
</tr>
<?php
$check=$_POST['check'];
if($_REQUEST['Next']=='Next'){
{
$sql="INSERT INTO loaddetails (dispatcharea,Customer, casenumber, weight,LOCStatus)
SELECT `crtd dept`,Customer,`case no`,`gross mass`,'in Load Creation'
FROM despgoods_alldetails WHERE `Case No` = '$val'";
foreach($check as $key=>$value)
{
$sql="INSERT INTO loaddetails (dispatcharea,Customer, casenumber, weight,LOCStatus)
SELECT `crtd dept`,Customer,`case no`,`gross mass`,'in Load Creation'
FROM despgoods_alldetails WHERE `Case No` = '$value'";
$final=mysql_query($sql);
if($final)
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=planlocalpmbstep2.php\">";
} }
}
}
// Check if delete button active, start this
// if successful redirect to php.php
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
The output of the above code is shown below:

As the others have said, you'll have to do this in Javascript, since it'll be on the client side. I'll assume that you're not using a library such as jQuery or Prototype on this page, and if this is all you're doing, it'd be massive overkill to use one of them.
First, add a HTML element which will contain your total:
<div>Total: <span id="total">0</span></div>
The bit of information you really need to know however, is the weight which corresponds to each checkbox. The simplest method would be to store it on the checkbox element itself. Add an attribute called data-weight. eg:
<input type="checkbox" name="check[]" value="12" data-weight="1234" />
Then, add some javascript:
<script>
(function () {
var totalEl = document.getElementById('total'),
total = 0,
checkboxes = document.form1['check[]'],
handleClick = function () {
total += parseInt(this['data-weight'], 10) * (this.checked ? 1 : -1);
totalEl.innerHTML = total;
},
i, l
;
for (i = 0, l = checkboxes.length; i < l; ++i) {
checkboxes[i].onclick = handleClick;
}
}());
</script>
Aaaannd here's a working demo for you! http://jsbin.com/ipeduf

Assuming you don't want to have to refresh the page every time the user changes a selection, you need to do this in the browser, in Javascript, not in PHP.

I think that you can use a javascript function.
Add an onClick attribute to every checkbox (if you don't want a submit button):
<INPUT TYPE="checkbox" NAME="switchBox" onclick="myfunction(this)">
Then myfunction should calculate the value with something like that:
<script language="javascript">
var total;
myfunction(checkboxId){
total = total + checkboxId.value;
}
</script>
Please notice that this is an unchecked example, only to give you an idea about a solution.

To avoid the need to submit and reaload the page on changes, I would use javascript / jQuery.
What I would do is:
attach all individual weight values to the table rows (or checkboxes...) using the html5 data attribute: <tr data-weight="1604"> for your first row;
on a checkbox value change, loop through all rows that have a selected checkbox to get and generate your sum. That would be something like:
$("input").change(function(){
var total_sum = 0;
$('input').is(':checked').each(function(){
total_sum += $(this).parents("tr").data("weight");
});
});
(can't get the formatting right...)
display the sum in the box you want.

Related

can't delete from specific row from generate table from mySQL

Hye, i'm working on a small project of Inventory system. Everything is okay until this last part. I have included a delete button at the end of each row for user to delete any item of choice, but when user press the delete button, it deleted the last row of the table, instead of the row/item of choices, where is my mistake in my coding?
Thank you!
<?php
$result= mysql_query("SELECT * from Staff ORDER BY status");
$count=1;
while($row=mysql_fetch_array($result)){
?>
<tr>
<td align="left"><?php echo $count; ?></td>
<td align="left"><?php echo $row['staffId']; ?></td>
<td align="left"><?php echo $row['name']; ?></td>
<td align="left"><?php echo $row['address'];?></td>
<td align="left"><?php echo $row['pNum'];?></td>
<td align="left"><?php echo $row['status'];?></td>
<td align="left"><?php echo $row['type'];?></td>
<td><input type="submit" name="deleteStaff" value="Delete" onClick="displayMessage()">
<input type="hidden" name="staffId1" value="<?PHP echo $row['staffId']; ?>">
</td>
</tr>
</tbody>
<?php
$count++; }
if(isset($_POST['deleteStaff'])){
$id=$_POST['staffId1'];
$result=mysql_query("DELETE from Staff WHERE staffId='$id' ");
if($result){
echo '<script> location.replace("viewStaff.php"); </script>';
}
else{
?>
<script>
alert ("Fail to delete data")
window.location.href='viewStaff.php'
</script>
<?PHP
}
}
?>
I've encountered this error before as well. I think the error is happening since you're calling the same "onclick" function for each array result.
Instead, create a link to a page where you can run the php deletion script and pass the staffID into the URI and Get that in the php deletion script that you created.
example
<form action="deletion_script.php?staffid=<?php echo $staffid; ?>">
Put that inside of the td tag
Then in your deletion_script.php file, put something like this
<?php
//get staffid from URI
$staffid = $_GET['staffid'];
$sql="DELETE FROM $table_name WHERE staffid = '$staffid'"
$result = mysqli_query($connect, $sql);
if($result) {
//send back to the page you want
header("Location: ../inventory.php");
}
?>
This worked for me, and how I handle all situations like this from now on. You'll need to adjust the code a little to fit your set up.
since the name for the hidden field is the same for all rows being generated the post request is pulling the value of the last row( also "staffId1" ).
I recommend either using a individual form for each row in which case your code doesn't change as much or use js to get the required staffID using selectors
If you include the same hidden field (StaffId1) for every record it will contain more then one value.
You are now listening to the pressed SUBMIT so you don't need the hidden field. You can just get the value if the pressed SUBMIT.
Button
type="submit" name="staffId" value="<?php echo $id ?>"
Php
$id=$_POST['staffId'];

How do I toggle a displayed database field with single click

I have a database table and one specific value is either a value of Yes or No represented by an icon of checkmark or X.
I want to be able to toggle this value with a single click rather then the current workflow where the user clicks the icon and then they are directed to update page where they toggle the value and then update.
The value is either Yes or No. I simply want to click it have the value change to the opposite value real time without refreshing.
Thank you
Here is the partial code for the display database, the field name is called 'enter'
<?php
include "db.inc.php";
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * 15;
$sql = "SELECT * FROM ircb ORDER BY id DESC LIMIT $start_from, 15";
$rs_result = mysql_query ($sql);
$num_rows = mysql_num_rows($rs_result);
$query = mysql_query("SELECT * FROM ircb");
$number=mysql_num_rows($query);
while($rows=mysql_fetch_array($rs_result)){
<tr bgcolor='#9B9D9F'>
<td><?= $rows['totalt'] ?></td>
<td><?= $rows['service'] ?></td>
<td><?= $rows['item'] ?></td>
<td align="center">
<a href="edit_form1.php?id=<?= $rows['id'] ?>">
<img src="backgrounds/bg/<?= $rows['enter'] ?>.png" border="0">
</a>
</td>
</tr>
The edit.form1
<form method="post" action="update1.php">
<input type="hidden" name="id" value=<?php echo "$row[id]"?>">
<tr>
<td>Entered</td>
<td>
<input type="radio" name="enter"
value=Yes>Yes<input type="radio" name="enter" value=No checked>No
</td>
</tr>
<hr />
<tr style="height: 20px"><td></td></tr>
<tr>
<td align="right">
<input class="button" type="submit"
value="Update">
</td>
The problem you are having seems to be because you are redirecting to a page that has a form to do the update. Instead of using a form, you could use the link directly to do the trick. The best way to do it is to have the href lead to the exact same page that displays the table, but adding query parameters to tell the scripts to toggle the required row.
Using this, you could check in your PHP, before querying the database to display the tables:
if($_GET['toggle_id']){
//$_GET['toggle_id'] = the ID of the line to modify
//Use the same script as the form handler
}
So instead of waiting for a value of YES or NO, you would figure it out yourself using the current value:
$nextValue = $currentValue=='NO'?'YES':'NO';
That should cover most of the logic.

How to change number values in PHP when radio button is check or click

I have 4 rows in a table.
Each row has 4 radio buttons.
Each radio buttons has value number [1, 2, 3, 4]
When user selects one of the radio buttons, it automatically prints the value in each row. Then I take each value and total them at the bottom of the table.
I'm guessing it can be done with javascript? But how?
Here's a sample PHP code for the row:
<input type="radio" name="a" value="1" <?php if($row['a'] == '1'){echo "checked";} ?>/>
I want to print out the value at the end of each row. Then total the each row's value at the bottom of the table.
Also, here's my php code to total all rows.
$total = $a + $b + $c + $d;
echo $total;
?>
Thanks! :)
Though I can't post any code at the moment (dehabilitating numeric keypad), the general method to dynamically update content dependent on a backend is to activate an AJAX call (or page refresh) whenever a checkbox's state is changed. The new state and/or unique parameters will be sent to your server, which will then echo (as per your request) out the new view.
From the information you've provided, it is difficult to determine whether the radio buttons dependend on any special backend model (database information).
If they are not, then we will assume that the checkboxes have unique IDs, prefixed with chk_, and that the text box you want to output the value to is called out. We will also assume that you are using jQuery.
var total = 0;
for (var i = 1; i <= 4; i++)
{
var e = $('#chk' + i);
if (e.is(':checked'))
{
total += parseInt(e.val());
}
}
$("#out").text(total);
EDIT: After the edit of your original post, this code is still valid. However, if you name your checkbox a like you have, you will need to revise the for loop in the above code. You may be able to loop through all radio buttons, or radio buttons inside a certain HTML element. The implementation is up to you.
All the calculations should made on client side as per your scenario. So in this case JavaScript will do the work.
Below code will calculate each row as per radio selection and also calculate total of all selections.
<html>
<head>
<script language="JavaScript">
<!--
function calculateRow(val1, val2)
{
var total = 0;
var ctr=1;
var divs=document.getElementsByTagName('div');
document.getElementById('selectedValue_'+val2).innerHTML = val1.value;
for(i=0;i<divs.length;i++)
{
divId = divs[i].id.substring(0,14);
if(divId == 'selectedValue_')
{
total += parseInt(document.getElementById('selectedValue_'+ctr).innerHTML);
ctr++;
}
}
document.getElementById('total').innerHTML = total;
}
//-->
</script>
</head>
<body>
<form name="frmScore">
<table border=1>
<tr>
<td>Select</td>
<td>Score</td>
</tr>
<?php
for($i=1;$i<=10;$i++)
{
echo "
<tr>
<td>
<input type='radio' value='1' name='test{$i}' onclick='calculateRow(this,{$i})'>
<input type='radio' value='2' name='test{$i}' onclick='calculateRow(this,{$i})'>
<input type='radio' value='3' name='test{$i}' onclick='calculateRow(this,{$i})'>
<input type='radio' value='4' name='test{$i}' onclick='calculateRow(this,{$i})'>
</td>
<td><div id='selectedValue_{$i}'>0</div></td>
</tr>";
}
?>
<tr>
<td>Total</td>
<td><div id='total'></div></td>
</tr>
</table>
</form>
</body>
</html>
Cheers!!!

Retrieve data from mysql and update them accordingly

I want to retrieve data from my MySQL database and display it as a table (I don't mind any style, but preferred as a table). Then the data should display with a radio button or a normal button which update that specific row and changing a single column in that row to Active (Status making Active).
I have started it, but I still have issues with adding a radio button or a button. Then I thought of displaying the information in a table which inside a form. This form will have each radio buttons, when the person select that radio button and press submit. The data should be updated in the MySQL database.
Can someone guide me about this? I'm a bit confused. I'm confused because I have to add a form and in that form I have to add a table and all this stuff should be in a php file.
on formpost.php page you can do something like this for handling the list array you received from the previous page:
<?
$list = $_POST['list'];
foreach ($list as $key => $list_php)
{
$query1 = "SELECT * FROM `stu_entry` WHERE `stu_entry`.`Student_No` = '$list_php' AND `stu_entry`.`Out_Time` = '0000-00-00 00:00:00'";
$result1 = mysql_query($query1);
$row1=mysql_fetch_array($result1);
//whatever you want to do
}
?>
I forgot to tell you something in the previous post. In the form page, lets say you have 100 rows with 100 checkboxes. It would be nasty to manually check or uncheck all of them. As an alternative you could append a little script at the end of the page to handle the checking/ unchecking process for you:
<script>
function checkAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = true ;
}
function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
field[i].checked = false ;
}
function countChecks(form){
var t=0;
var c=form['list[]'];
for(var i=0;i<c.length;i++){
c[i].checked?t++:null;
}
return t;
}
</script>
<input type="button" name="CheckAll" value="Check All"
onClick="checkAll(document.formpost['list[]'])">
<input type="button" name="UnCheckAll" value="Uncheck All"
onClick="uncheckAll(document.formpost['list[]'])">
<i>with selected: </i>
<select name="submit_mult" id="submit_mult">
<option value="todo1">Action 1 </option>
<option value="todo2">Action 2 </option>
</select>
<input type="button" name="go" value="Go" onClick='if(countChecks(this.form)>0) {if(confirm("are you sure you want to \""+document.getElementById("submit_mult").options[document.getElementById("submit_mult").selectedIndex].text+" "+countChecks(this.form)+" items selected"+"\"")) {document.getElementById("referenceToSomeHiddenElement").value=document.getElementById("submit_mult").options[document.getElementById("submit_mult").selectedIndex].value;document.getElementById("formpost").submit();}} else alert("you have not selected any item!!")' >
Tell me if you need more help on this.
I first specify a MySQL command which in return gives me an array. I use a while statement to do something to each item in the array. The array is populated with the field name and the field contents.
$mysql = mysql_query("SELECT * FROM table");
while ($array = mysql_fetch_array($mysql))
{
$output .= '<form>Row: ' . $array['fieldname'] . ' <input type="button" value="Update" /></form>';
}
This extracts all rows from the table and adds a form to the variable $output for every result. I'm unsure of how you want to update your database, so you will have to look into it. You can use GET and POST methods.
Go ahead and try something like this. And tell me if that worked:
<p><b>your page name</b></p>
<form name="formpost" id="formpost" action="formpost.php" method="POST">
<table border="2" cellpadding="5" cellspacing="1" style="border-collapse: collapse" bordercolor="#999999" width="800">
<tr>
<td><b>Sno.</b></td>
<td><b>Field name1</b></td>
<td><b>Field name2</b></td>
<td><b>Field name3</b></td>
<td><b>Field name4</b></td>
<td><b>Field name5</b></td>
<td><b>Field name6</b></td>
<td><b>Field name7</b></td>
</tr>
<?
$sorting="";
if($orderby!="" && $direction!="") $sorting=" ORDER BY $orderby $direction";
$query = "SELECT * FROM table WHERE something = 'something' $sorting";
$result = mysql_query($query);
?>
<tr>
<?
$i=0;
while ($row = mysql_fetch_array($result))
{
$i++;
?>
<td><input type="checkbox" name="list[<?echo $i?>]" id="list[]" value="<?echo $row['some_primary_field_id']?>"><?echo $i?></td>
<td><?echo $row['Field1']?></td>
<td><?echo $row['Field2']?></td>
<td><?echo $row['Field3']?></td>
<td><?echo $row['Field4']?></td>
<td><?echo $row['Field5']?></td>
<td><?echo $row['Field6']?></td>
<td><p align="center">
<?
echo "<input title='button' name='change this row' value='Some Button' type='button' onClick=\"if(confirm('Press OK to change status to confirm')) {document.getElementById('someid').value='".$row['Field1']."';document.getElementById('formpost').submit();}\"/>";
?>
</td>
</tr>
<input type='hidden' name="hiddenlist[<?echo $i?>]" id="hiddenlist[]" value="<?echo "some boundry condition ".$row['Field2']?>">
<?
} //end of while
?>
</table>
</form>

how to update and post the value of checkbox from ajax call

i retrieved data from mysql table into html page i.e
$query="select * from student";
$result=mysql_query($query)or die(mysql_error());
while($rs=mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><?php echo $rs['st_id']; ?></td>
<td align="center"><?php echo $rs['name']"; ?></td>
<td align="center"><input type="checkbox" name="checked[]" <?php if($rs['checked']==1){echo "checked"; } ?> /></td>
<td align="center"><img src="images/delete_icon.png" alt="Delete" /></td>
<td align="center"><img src="images/update.png" alt="Update" /></td>
this is gives me the output
assume that checkbox of id 1 is checked and retrieved from mysql table.
Now what i want to do is that when i checked the remaing two checkbox into this table and a function is called to ajax which goes to php page and update the value of checked field according to the given id (i.e 2 and 3 in this case). Not refreshing the whole page nor updating the whole record just the value of check box. i am new to ajax so
any help would be greatly appreciated.
Yes, exploring jqGrid isn't a waste of time at all. However, since you want to update only on change of checkbox value. Here's what you can do..
<input type="checkbox" name="check1" />
And..
$().ready(function(){
var st_id = <?php echo $rs['st_id']; ?>;
//Or you could use a hidden field in the form
$(':checkbox').click(function(){
var chkName = $(this).attr('name');
var checkVal = $(':checkbox[name='+chkName+']').attr('checked');//true or false
$.ajax({
url: 'MyApp/update.php?checboxName=' + checkVal,//Do update on server-side
success: function(data) {
alert('Updated successful.');
}
});
});
});
Also, you can do a $('formID').serialize() wihch returns name=value pairs of all form elements that can then be appended in the call to your php script.

Categories