toggle a value in database based on user input of check box - php

I have a list of items that will be fetched from DB. Each row have one checkbox and an associated value in DB. If it is checked and saved the value changes to 1 else it will be 0.
So on page load there is a drop down to select the items.Based on the selection, the data will be fetched. Values with 1 will be shown checked and 0 will be unchecked.
I am trying to update this to DB on button click. So newly checked ones will be saved with status 1 and unchecked will be updated with status 0.
If one value was previously 1 and is unchecked during update, the value should change to 0.
My code:
HTML:
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<tbody>
<tr class="even pointer" id="<?php echo $row['tcode'] ?>">
<td class="a-center ">
<?php if($row['selected'] == 0){ ?>
<input class="flat" type="checkbox" name="check_list[]" value="<?php echo $row['tcode'] ?>">
<?php } else{ ?>
<input class="flat" type="checkbox" name="check_list[]" value="<?php echo $row['tcode'] ?>" checked>
<?php } ?>
</td>
<td class=" "><?php echo $row['task_name'] ?></td>
<td class=" "><?php echo $row['tcode'] ?></td>
<td class=" "><?php echo $row['task_category'] ?></td>
</td>
</tr>
</tbody>
<?php } ?>
PHP:
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
$projectcode=$_POST['projectcategory'];
// Loop to store and display values of individual checked checkbox.
echo $_POST['check_list'];
foreach($_POST['check_list'] as $selected){
$sql2="UPDATE mappedtask SET selected=1 WHERE pcode = '$projectcode' AND pcode = '.$_POST[tcode].' ";
$result2=$conn->query($sql2);
}
}
}

Related

Using a PHP foreach loop within another foreach loop

I am trying to populate a table with rows from a database. However, one of the columns is a dropdown that needs to be populated with more than one value, therefore needing to use fetchAll. However, I am having trouble since I am using a foreach construct inside another foreach construct.
I'm guessing this isn't possible, or am I just doing something wrong? How can I find a workaround so that I can populate the entire table while also populating the dropdown with more than just one value, but still having it default to the value that it is in the database?
<?php
$sql = "SELECT TOP 100 *
FROM Table_OS_List
ORDER BY [CURRENT_SKU] ASC";
$drops = "SELECT [Purchasing_Group]
FROM Table_OS_List
GROUP BY [Purchasing_Group]";
$drop = $dbh->query($drops);
?>
<?php
/* Foreach loop that brings in information to populate table */
foreach ($dbh->query($sql) as $rows) {
?>
<tr class="row">
<td class="old_sku" id="old_sku"><?php echo intval ($rows['OLD_SKU'])?></td>
<td class="current_sku" id="current_sku"><?php echo intval ($rows['CURRENT_SKU'])?></td>
<td class="id" id="id" style="display: none;"><?php echo intval ($rows['ID'])?></td>
<td class="dropdown-select" id="purchgroup">
<select id="selected_group" class="selected_group" disabled>
<?php foreach($drop->fetchAll() as $dropdown) { ?>
<option class="choice" value="Purchasing Group"><?php echo $dropdown['Purchasing_Group'];?></option>
<?php } ?>
</select>
</td>
<td><input type="button" class="edit" name="edit" value="Edit"></td>
<td><input type="button" class="delete" name="delete" id="<?php echo intval ($rows['ID'])?>" value="Delete"></td>
</tr>
<?php
}
?>
NOTE
This code correctly populates the entire table, however the dropdown list only has the value that is in each row and is not populated with the other value options if I need to select something different:
<?php
/* Foreach loop that brings in information to populate table */
foreach ($dbh->query($sql) as $rows) {
?>
<tr class="row">
<td class="old_sku" id="old_sku"><?php echo intval ($rows['OLD_SKU'])?></td>
<td class="current_sku" id="current_sku"><?php echo intval ($rows['CURRENT_SKU'])?></td>
<td class="id" id="id" style="display: none;"><?php echo intval ($rows['ID'])?></td>
<td class="dropdown-select" id="purchgroup">
<select id="selected_group" class="selected_group" disabled>
<option class="choice" value="Purchasing Group"><?php echo $rows['Purchasing_Group'];?></option>
</select>
</td>
<td><input type="button" class="edit" name="edit" value="Edit"></td>
<td><input type="button" class="delete" name="delete" id="<?php echo intval ($rows['ID'])?>" value="Delete"></td>
</tr>
<?php
}
?>
EDIT:
Each dropdown is automatically defaulting to Bowling Green even if that row should not be Bowling Green. Most rows are either Southeast or Michigan but regardless of what it should be, it is defaulting to Bowling Green for some reason
Yes, doing it wrong, you are consuming the second resultset on completion of the first iteration of the outer foreach so instead retrieve the dropdown contents into an array so you can reuse it many times
<?php
$sql = "SELECT TOP 100 *
FROM Table_OS_List
ORDER BY [CURRENT_SKU] ASC";
$drops = "SELECT [Purchasing_Group]
FROM Table_OS_List
GROUP BY [Purchasing_Group]";
$drop = $dbh->query($drops);
$allDrops = $drop->fetchAll();
?>
<?php
/* Foreach loop that brings in information to populate table */
foreach ($dbh->query($sql) as $rows) {
?>
<tr class="row">
<td class="old_sku" id="old_sku"><?php echo intval ($rows['OLD_SKU'])?></td>
<td class="current_sku" id="current_sku"><?php echo intval ($rows['CURRENT_SKU'])?></td>
<td class="id" id="id" style="display: none;"><?php echo intval ($rows['ID'])?></td>
<td class="dropdown-select" id="purchgroup">
<select id="selected_group" class="selected_group" disabled>
<?php
foreach($allDrops as $dropdown) {
//--------------^^^^^^^^^
// Also changed the way you fill the option tag below
?>
<option class="choice"
value="<?php echo $dropdown['Purchasing_Group'];?>">
<?php echo $dropdown['Purchasing_Group'];?>
</option>
<?php } ?>
</select>
</td>
<td><input type="button" class="edit" name="edit" value="Edit"></td>
<td><input type="button" class="delete" name="delete" id="<?php echo intval ($rows['ID'])?>" value="Delete"></td>
</tr>
<?php
}
?>

Passing Check Box Value in PHP by using ahref tag

I have a php flie that connects the database and selects the table login_info and retries the login details like email ,name,row id and level and with the result I have shown a table having a check box and I want to pass check box value by href tag.
Below given code:
<?php
include("../script/config.php");
$sql = "select * from login_info";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$username=$row['username'];
$useremail=$row['useremail'];
$level=$row['level'];
$id=$row['id'];
<tr>
<td class="style3"><div align="left" class="style9 style5">
<div align="center"><strong><?php echo $username; ?></strong></div>
</div>
</td>
<td class="style3"><div align="left" class="style9 style5"><div align="center"><strong><?php echo $useremail; ?></strong></div></div>
</td>
<td class="style3"><div align="left" class="style9 style5">
<div align="center">
<input name="checkbox" type="checkbox" value="1"
<?php
if ($level==1)
{
echo 'checked' ;
}
else
{
echo 'unchecked';
}
?>
/>
</div>
</div>
</td>
<td class="style3"><div align="left" class="style9 style5">
<div align="center"><strong>
<a href="../script/Edit_user.php?Id=<?php echo $id;?>&checkbox=<?php echo $checkbox;?>">
<img src="../images/update.jpg" width="42" height="40" u="image" /></a></strong></div>
</div>
</td>
?>
Create a variable and then use it as you like.
$isChecked = ($level == 1 ? 'checked' : 'unchecked');
<input name="checkbox" type="checkbox" value="1" <?php echo $isChecked; ?>/>
<a href="../script/Edit_user.php?Id=<?php echo $id;?>&checkbox=<?php echo $isChecked;?>">

Keep checkboxes in array checked on form submit

I have a list of checkboxes created by a while loop but when the form is submitted the checkboxes are cleared. I have tried to use the unique id of the value in the record by putting it in a hidden field and then using it in an if query before marking the checkbox as checked but it does nothing
<?php
while($row = mysqli_fetch_array($result)){
$posted = $row['auditID'];
?>
<tr class="hover">
<td width="180"><? echo $row['auditName']; ?>
<input type="hidden" name="audit_id_confirm" value="<? echo $row['auditID'];?>">
</td>
<td width="33"><input type="checkbox" name="audit_selected[]"
value="<? echo $row['auditID'];?>"
<?php if($_POST['audit_id_confirm'] == $posted){ echo "checked"; }?>>
</td>
</tr>
<?php
}
?>
I sorted it by checking id=f the id number was in the arrays that had been posted.
<?php
$selected = $_POST['audit_selected'];
while($row = mysqli_fetch_array($result)){
$audit = $row['auditID'];
if(in_array($audit, $selected)) {
$check="checked='checked'";
}else{
$check = '';
} ?>
<tr class="hover">
<td width="180">
<?php echo $row['auditName'].' '.$num_audited; ?></td><td width="33"> <input type="checkbox" name="audit_selected[]" value="<?php echo $row['auditID'];?>" <?php echo $check; ?> >
</td>
</tr>
<?php }
?>
<?php if($_POST['audit_id_confirm'] == $posted){ echo "checked"; }?>>
Replace above line with this:
<?php if($_POST['audit_id_confirm'] == $posted){ echo "checked='checked'"; }?>>
You are not properly providing checked attribute to the Html entity.
One of the information you need to store in the table, is the state of the checkbox.
So, you can create a new column in your table, call it "checkboxstate".
Now inside your code use the following code to insert the checkbox:
<input type="checkbox" name="<?php echo($posted); ?>">
Thus far we have created several checkboxes whom names are the same as $posted, in other words each checkbox will have the name of its row's "$posted" value.
Now the only thing that is left is submitting the form and storing the checkbox info, which will return either TRUE or FALSE, and we will save that in our table, in the "checkboxstate" column.
So now in our table we will have a bunch of rows with several columns, one of the columns will be "checkboxstate" whom value will be either TRUE or FALSE.
At this point we have pretty much solved the problem, all that is left is to insert a simple if to either show a checked checkbox or an unchecked one.
<?php
while($row = mysqli_fetch_array($result)){
$posted = $row['auditID'];
$cbs = $row['checkboxstate'];
?>
<tr class="hover">
<td width="180"><? echo $row['auditName']; ?></td>
<td width="33">
<?php if($cbs == "true") echo "<input type='checkbox' name='$posted' checked='checked'>"; else echo "<input type='checkbox' name='$posted'>";
</td>
</tr>
<?php
}
?>

Post values of single row from while loop using onclick

I am trying to pass the column values from a single row generated from a while loop. When the link is clicked I want certain values from that row to be passed as hidden fields to another page.
The code:
<form id="repeat" name="repeat" action="edit_user.php" method="post">
<?php
$counter = 0;
while($row = $result->fetch_array()) {
$color = ($counter & 1)? "#D7ECEC" : "#DEDEDE";
$counter++;
?>
<tr align="left" valign="middle" style="background: <?php print $color; ?>">
<td><a href="#" onclick="document.getElementById('repeat').submit();" >
<?php echo $row['firstname']; ?> <?php echo $row['surname']; ?></a></td>
<td><?php echo $row['userlogin']; ?></td>
<td><?php echo $row['accesslvl']; ?></td>
<td ><?php echo $row['chgpasswrd']; ?></td>
</tr>
<input type="hidden" name="id" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="lvl" value="<?php echo $row['accesslvl']; ?>" />
<?php } ?>
</table>
</form>
What is happening is that the hidden fields are passing values for the last row of the while loop. Is it possible to do this so the hidden values being passed are from the same row of the link that is being clicked?
I've tried a few things and nothing works and I've not been able to find anything that directly relates to this problem. Any help would be appreciated. Cheers
You need to split this into two pages really. The first page displays the user info and link for each unique user, and the second page provides the edit form for posting the form data as follows...
<table>
<?php
$counter = 0;
while($row = $result->fetch_array()) {
$color = ($counter & 1)? "#D7ECEC" : "#DEDEDE";
$counter++;
?>
<tr align="left" valign="middle" style="background: <?php print $color; ?>">
<td>
<a href="edit_user.php?userID=<?php echo $row['userID']; ?>&accesslvl=<?php echo $row['accesslvl']; ?>">
<?php echo $row['firstname']; ?> <?php echo $row['surname']; ?>
</a>
</td>
<td><?php echo $row['userlogin']; ?></td>
<td><?php echo $row['accesslvl']; ?></td>
<td ><?php echo $row['chgpasswrd']; ?></td>
</tr>
<?php } ?>
</table>
on the edit_user page you can populate the hidden fields with the information passed in by the url query string. Remember to clean the values to prevent sql injection or xss attacks. I've used htmlentities here as an example and you may want to enhance this, read the php documentation page on htmlentites for more information (ENT_QUOTES).
$userID = htmlentities($_GET['userID']);
$accesslvl = htmlentities($_GET['accesslvl']);
<form action="modify_user.php" method="post">
<input type="hidden" name="id" value="<?php echo (int)$userID; ?>" />
<input type="hidden" name="lvl" value="<?php echo $accesslvl; ?>" />
//rest of form html

using PHP for each to get dynamic values from table

It's been a while since I looked at php and I've got a brain block. I'm trying to get the values from a table using foreach so that I can store the values in a session and also display the number of items that have been ordered.
eg 2 of item number 4 etc
here's the table / form
<form id="products" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
//every item from the products table is queried because all fields need to be displayed
$sSQL = "SELECT * FROM products";
$rsResult = mysql_query($sSQL);
?>
<table id="products_table">
<tr style="font-weight:bold">
<td style="text-align:center">ID</td>
<td>Ref No.</td>
<td>Product Name</td>
<td>Description</td>
<td style="text-align:right">Price</td>
<td colspan='2' style='text-align:center'>Add To Order</td>
</tr>
<!--for each record in the table that matches the query a row is created in the table and the data in the relevant field is displayed-->
<?php while ($row = mysql_fetch_array($rsResult)){ ?>
<tr>
<input type="hidden" name="productID[<? echo $row['productID']; ?>]" value="<? echo $row['productID']; ?>" />
<td style="text-align:center"><? echo $row['productID']; ?></td>
<td><? echo $row['productReference']; ?></td>
<td><? echo $row['productName']; ?></td>
<td><? echo $row['productDescription']; ?></td>
<td style="text-align:right"><? echo '£'. $row['productPrice']; ?></td>
<td style="text-align:center"><span>Qty</span><input type='text' name="qty[<? echo ($_POST['qty']); ?>]" value="" ></td>
<? } ?>
</table>
Heres the php
<?php
foreach($_POST as $key => $value){
echo $key . ' ' .$value.'<br />';
print_r($key);
}
?>
I know that the php is no where complete for filling sessions etc, I just can't work out how to get the values out of the form. This php was my attempt to try and at least get some kind of value out of it
Any help is greatly appreciated
in your code , there is no need of
<input type="hidden" name="productID[<? echo $row['productID']; ?>
field .
also change the line
<td style="text-align:center"><span>Qty</span><input type='text' name="qty[<? echo ($_POST['qty']); ?>]" value="" ></td>
to
<td style="text-align:center"><span>Qty</span><input type='text' name="qty[<? echo ($row['productID']); ?>]" value="" ></td>
so that after the submission of the form , you can access the posted values with :
$sSQL = "SELECT * FROM products";
$rsResult = mysql_query($sSQL);
while ($row = mysql_fetch_array($rsResult))
{
echo $_POST['qty'.$row['productID']];
}
why don't you just display data in inputs with proper names?

Categories