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.
Related
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'];
I am actually starting my newest codes with HTML/PHP .
I am searching for retrieving data (list of persons) from mysql Data Base, displaying it into html table, then when I will clik on button "edit" it will show me in another page the details of the selected person like this :
It works fine for all the rows expects the firt row of the table.
Any help please !!!
there is my code :
<table border = 1>
<caption> Liste des personnes </caption>
<tr>
<th>id </th>
<th>nom</th>
<th>prenom</th>
<th>date Naissance</th>
<th>sexe</th>
<th>ville</th>
<th>comptence</th>
<th>photo</th>
</tr>
<?php while ($obj = mysqli_fetch_object($result)){ ?>
<tr>
<td> <?= $obj->id ?> </td>
<td><?= $obj->nom?></td>
<td><?= $obj->prenom?></td>
<td><?= $obj->dateNaissance?></td>
<td><?= $obj->sexe?></td>
<td><?= $obj->ville?></td>
<td><?= $obj->competence?></td>
<?php if (isset($obj->photo)) {?>
<td><img src="uploads/<?= $obj->photo?>" width =20 height = 20 >
<?php } ?>
<td>
<form name="editPerson" action="edit.php" method="POST">
<input type="hidden" name="id" value="<?= $obj->id ?>">
<input type="submit" name="editer" value="Edit">
</form>
</td>
</tr>
<?php } ?>
</table>
Explainations
You can't have an action='edit.php' as you will edit a specific user, not all of them. You need to specify in your action what user you want to edit. And it is mostly done with the ID of the user. So you action will look like this action='edit.php?id=1. And so, your method would be GET.
In your edit.php, you will have a $_GET['id'] variable that will contain the ID of the user to be edited. So you will have to first create a new query to search for this specific user.
You can then proceed on preparing the query.
$query = $connexion->prepare('SELECT * FROM users WHERE id = :id');
And then, executing the query with the id from the URI.
$query->execute(['id' => $_GET['id']]);
And cast the result to a variable to get the user.
Then, all you have to do in your page is a little bit of refactoring from your previous page. Meaning that there will be now a big <form> tag surrounding your <table> tag and the <td> tag will now contain <input value='<?php $user->id; ?>'> tag for example for the ID. And your edit buttons will now be a save button.
The method of the <form> in your edit?id=1 would be a POST method ot itself. So in the same page, you will be able to update the user. You can also cast the form to another page, like saveUser.php. Just be consistent from one solution to another in all your project.
<form method='POST' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
Use this Code
<input type="submit" name="editer" value="Edit">
Instead of
<form name="editPerson" action="edit.php" method="POST">
<input type="hidden" name="id" value="<?= $obj->id ?>">
<input type="submit" name="editer" value="Edit">
</form>
And get the id value on edit.php file by using $_GET['id'].
Example for edit.php file:
$id = $_GET['id']
i define below codes to show my products on website. I fetch my products details from Database.
When i click on the enquiry submit button it is not selecting the same id and inserting another product id in to database. Please see below codes which i use to send details in database using enquiry Submit Button
Please see below the updated codes, these are all codes which i am using to inserting data when clicking on enquiry submit button
<?php
session_start();
include'database.php';
$userid=$_SESSION['userid'];
$c=mysql_query("select 'productid','productprice' from products order by rand()");
while(list($productid,$productprice)=mysql_fetch_array($c)):
?>
<td align="center">
<table class="newproducttd" align="center">
<tr>
<td class="code" align="center"><?php echo $productid; ?></td>
<td class="price" align="center"><?php echo $productprice; ?></td>
</tr>
<tr>
<td class="button" align="center"><input type="submit" class="enquiry" name="enquiry" value="ENQUIRY" /></td>
</tr>
</table>
</td><br>
<?php
endwhile;
if($_REQUEST['enquiry'])
{
mysql_query("insert into orders values('$userid','$productid','$productprice')");
}
?>
Your table in your mysql database probably has the columns in a different order. To make sure, specify the columns in your insert query before specifying the values.
You're getting the wrong value for $productid because it's assigning the last value of it in your while loop, as your insertion code (and therefore your reference to it) is below that loop, you want to send the product id and price to the page accessible by $_REQUEST when the user clicks submit, to do this in your case you can use hidden form fields to store the values of each product, and a separate form for each element in your loop.
Also you want to put your submission code above your loop.
Depending where this data comes from you might want to escape it before inserting it in the database, I haven't in this example.
<?php
session_start();
include'database.php';
$userid=$_SESSION['userid'];
//check for submission and insert if set
if($_REQUEST['enquiry'])
{
//use the userid session for userid, and submitted values for productid and productprice
mysql_query("insert into orders values('$userid,'{$_REQUEST['productid']}','{$_REQUEST['productprice']}')");
}
$c=mysql_query("select 'productid','productprice' from products order by rand()");
while(list($productid,$productprice)=mysql_fetch_array($c)):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<td align="center">
<table class="newproducttd" align="center">
<tr>
<td class="code" align="center"><?php echo $productid; ?></td>
<td class="price" align="center"><?php echo $productprice; ?></td>
</tr>
<tr>
<td class="button" align="center"><input type="submit" class="enquiry" name="enquiry" value="ENQUIRY" /></td>
//hidden form fields to store data to send to page
<input type="hidden" name="productid" value="<?php echo $productid;?>">
<input type="hidden" name="productprice" value="<?php echo $productprice;?>">
</tr>
</table>
</form>
<?php
endwhile;
?>
I wonder whether someone may be able to help me please.
Firstly, this is something I've never tackled before, so please bear with me if this is something which is straight forward to the more seasoned developer.
The code below is a portion of a script which correctly shows a 'Locations List' for each user.
$i=0;
while ($i < $num) {
$lid=mysql_result($result,$i,"locationid");
$lname=mysql_result($result,$i,"locationname");
$laddress=mysql_result($result,$i,"returnedaddress");
include("admin/link.php");
include("admin/opendb.php");
$fquery = "SELECT COUNT(*) num FROM finds WHERE locationid = '$lid'";
$fcount = mysql_query($fquery) or die('error');
$row = mysql_fetch_assoc($fcount);
$findscount = $row['num'];
mysql_close($connect);
?>
<table width="603" border="0">
<tr>
<th width="156">Location</th>
<th width="302">Address</th>
<th width="131">No. Of Finds Made</th>
</tr>
<tr>
<td><?php echo $lname;?></td>
<td><?php echo $laddress;?></td>
<td><?php echo $findscount;?></td>
</tr>
</table>
<?php
echo'<form name="locations" method="post">';
$i++;
}
if ($num == 0) {
echo"<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td colspan='3'><div align='center'><strong>No locations have been added yet. <a href='saveaddress.php'>Click here</a> to add one.</strong></div></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>";
}
echo '<input type="submit" name="submitlocation" id="submitlocation" value="View/Amend Location Details">';
echo '<input type="submit" name="submitfinds" id="submitaddfinds" value="Add Finds">';
echo '</div>'."\n";
if(isset($_POST["submitlocation"])) {
header("updatelocation.php");
}
else if(isset($_POST["submitaddfinds"])) {
header("addfinds.php");
}
?>
What I'm trying to do is add two submit buttons for each Location record, one which takes the user to a page called updatelocation.php and the second which takes the user to a page called addfinds.php. But both must be linked to the Location via the field 'locationid'. So in other words if the user wants to Add Finds for Location 1 upon clicking on the relevant button, they are taken to the Add Finds page for Location 1.
I've read a number of tutorials, but I've obviously misunderstood somewhere along the lines because although I've managed to add the buttons to the record, when I click either button the 'Locations List is refreshed, rather than the user being taken to the respective page.
I just wondered whether someone could possibly have a look at this please and let me know where I'm going wrong?
Many thanks and kind regards
You'd be better off making a seperate page (i.e., forrmaction.php) which processes the logic and sends the user to the correct page. If you do not want to do that, you can also make a seperate form for each button and simply set the action attribute of form to point to either updatelocation.php or addfinds.php
Example of formaction.php:
if (isset($_POST['type']) {
if ($_POST['type'] == 'update')
$url = 'updatelocation.php';
else
$url = 'addthis.php';
header("Location: " . $url);
}
Example of form with two buttons that works with formaction.php:
<form name="locations" method="POST" action="formaction.php">
<input type="submit" name="type" value="update">
<input type="submit" name="type" value="add">
</form>
However, for your question, the problem is that you are not using the correct header. To use a redirect, you must use "Location:" in the header. For example,
header("Location: updatelocation.php");
Be careful, because this will not work if headers have already been sent. You may want to look into output control in that case.
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.