retrieving multiple values from checkbox and hidden field - php

my code works as expected but a little issue occurred, i try retrieving values from checkboxes with same name and hidden fields with the same name, it works but one of the hidden field keeps on returning the first value even if the checkbox was not selected.
here is my code
while($row=mysql_fetch_array($res1)){
?>
<tr><td class='bold'><?php echo $sn;?><input type="hidden" name="snum[]" value="<?php echo $sn; ?>" /></td>
<td><?php echo $row['subLocationName']; ?>
<input type="hidden" name="location[]" value="<?php echo $row['dllink_id']; ?>"/></td>
<td><input type="checkbox" name="available[]" value="<?php echo $row['subLocationName']; ?>"/></td>
<input type="hidden" name="locationID[]" value="<?php echo $row['locationName']; ?>"/>
<input type="hidden" name="sublocation[]" value="<?php echo $row['subLocationName']; ?>"/>
<input type="hidden" name="device[]" value="<?php echo $row['deviceName']; ?>"/>
<td></td><td></td></tr>
<?php
$sn++;
}
the values are from my database.
the retrieving code is this
if(isset($_POST['submit_btn'])){
$serial_num = $_POST['snum'];
$locationDeviceLink = $_POST['location'];
$linkAvailable =$_POST['available'];
$location = $_POST['locationID'];
$subLocation = $_POST['sublocation'];
$device = $_POST['device'];
$measure_date = date("Y-m-d");
$sn = count($linkAvailable);
for ($i=0; $i<$sn; $i++ ){
if(!empty($linkAvailable[$i])){
echo "serial number:".$serial_num[$i]." location:".$locationDeviceLink[$i]." available:".$linkAvailable[$i]." Location:".$location[$i]." subLocation:".$subLocation[$i]." Device:".$device[$i]." Date:".$measure_date."<br/>";
}
}
}
the problem is the subLocation value, it keeps returning the first value then the second as it appears even if the associated checkbox is not checked and another checkbox is checked, please can anyone help me out, cant't think of anything more.
thanks in advance
joseph O

Rather then testing for !empty try using php's function isset.
for ($i=0; $i<$sn; $i++ ){
if(isset($linkAvailable[$i])) {
echo "serial number:".$serial_num[$i]." location:".$locationDeviceLink[$i]." available:".$linkAvailable[$i]." Location:".$location[$i]." subLocation:".$subLocation[$i]." Device:".$device[$i]." Date:".$measure_date."<br/>";
}
}

Related

looped list always inserts first in list using checkboxes

I have a list that is populated from a database table as below.
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td>
<input type="checkbox" name="name[]" value="<?php echo
$row['AnalysisID']; ?>">
<?php echo $row["CustomerName"]; ?>
<input type="hidden" name="Site[]" value="<?php echo $row["Site"]; ?>">
<input type="hidden" name="Unit[]" value="<?php echo $row["Unit"]; ?>">
</td>
<td><?php echo $row['Site']; ?></td>
<td><?php echo $row['Unit']; ?></td>
</tr>
<?php
}
?>
This displays the data perfectly, and in inspect all data is correct.
However I want to be able to check the various check-boxes and insert those rows to another table.
to achieve this I am using:
$counter = count($_POST["name"]);
for($x=0; $x<=$counter; $x++){
if(!empty($_POST["name"][$x])){
$PI_NO = mysql_real_escape_string($_POST["name"][$x]);
$CUSTOMER_NAME = mysql_real_escape_string($_POST["Site"][$x]);
$PI_ADDRESS = mysql_real_escape_string($_POST["Unit"][$x]);
$qry="INSERT INTO test1 (AnalysisID, Elem, Lube) VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
}
}
The problem is it doesn't matter what rows I check it always inserts the first in the list, it inserts the correct number just from the start of the list.
For example if I check the last 4 in the list I get the first 3.
Any pointers would be a great help.
Checkbox values are only sent if the checkboxes are checked, so the index will be different in the $_POST["name"] and the other $_POST arrays.
(Unchecked checkbox inputs are seen as "unsuccessful" https://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.2 )
Try adding the ID as index instead, then selected data will keep together.
(I renamed the name array to aid to better match the contents)
<td>
<input type="checkbox" name="aid[<?php echo $row['AnalysisID']; ?>]" value="1">
<?php echo $row["CustomerName"]; ?>
<input type="hidden" name="Site[<?php echo $row['AnalysisID']; ?>]" value="<?php echo $row["Site"]; ?>">
<input type="hidden" name="Unit[<?php echo $row['AnalysisID']; ?>]" value="<?php echo $row["Unit"]; ?>">
</td>
Then looping through the post data with foreach(). Only the checked ID's will be posted so no need for if (!empty() check.
if (isset($_POST["aid"])) { // to avoid php undefined notice if none selected
foreach ($_POST["aid"] as $id=>$value){ // the index is what we need, using $id
$PI_NO = mysql_real_escape_string($id);
$CUSTOMER_NAME = mysql_real_escape_string($_POST["Site"][$id]);
$PI_ADDRESS = mysql_real_escape_string($_POST["Unit"][$id]);
$qry="INSERT INTO test1 (AnalysisID, Elem, Lube) VALUES ('$PI_NO','$CUSTOMER_NAME','$PI_ADDRESS')";
mysql_query($qry);
}
}
Also I strongly advice you to change from using deprecated mysql_* functions, use mysqli or PDO instead. Why shouldn't I use mysql_* functions in PHP?

PHP- how to get values from checked checkboxes and corresponding textboxes

I want to get three values separated by a comma when the form is submitted. The value from the checkbox, textbox 1 and textbox 2.
This is my code that retrieves values from mysql database and generates checkboxes and two corresponding textboxes.
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$query = "SELECT * FROM subject";
$data = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($data)){
$s = $row['sub'];
echo $s;
?>
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="<?php echo $s; ?>" placeholder="Total Number" />
<input type="text" name="<?php echo $s; ?>" placeholder="Pass Number" />
<?php
}
?>
<input type="submit" name="submit" value="Add">
</form>
Suppose the user checks the first three boxes , and enters the values like in this picture -
when I click add, I get the values --
Physics
Math
Chemistry
by using the code below:
<?php
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
echo $selected."</br>";
}
}
}
?>
but how do I get the values like this-
Physics,40,30
Math,40,30
Chemistry,30,25
I want this output in a variable so that I can store it in my database table.
I have spent several hours behind this in last few days. Please help me with this one.
you need to assign unique names to the <input type="text" ... /> so you can recieve its values in the PHP.
Second, you need to write PHP code, that's concatenating those values.
For example, your HTML code might be:
<input type="checkbox" name="req_sub[]" value= "<?php echo $s; ?>" />
<input type="text" name="total[<?php echo $s; ?>]" placeholder="Total Number" />
<input type="text" name="pass[<?php echo $s; ?>]" placeholder="Pass Number" />
and your PHP code might be:
if (isset($_POST['submit'])) {
if (!empty($_POST['req_sub'])) {
foreach ($_POST['req_sub'] as $selected) {
$total = $_POST['total'][$selected];
$pass = $_POST['pass'][$selected];
$var = $selected . ',' . $total . ',' . $pass;
echo $var . '<br />';
}
}
}

Send values to db when multiple checkboxes are checked

I am loading some data from a db table to checkboxes. When a user checks boxes and submits, the values from these checkboxes need to be added to a different table. With the code I have now, I am able to send values of one checked box. What am I missing in sending the values of all the checked checkboxes?
<table>
<?php
$q5=mysqli_query($link,"SELECT * FROM brands_offer WHERE Brand_Id='$bid' AND Published='1' ");
while($row5 = mysqli_fetch_array($q5)){
$catid= $row5['Catg_Id'];
$subcatid= $row5['Subcatg_Id'];
$pid= $row5['Product_Id'];
?><tr><td>
<form action="store-admin.php?search=<?php echo $stname;?>#stock" method="post">
<input type="checkbox" name="checkbox" value="<?php echo "$bname,$catid,$subcatid,$pid";?>" >
<?php
echo $bname;
echo " -> ";
echo $catid;
echo ", ";
echo $subcatid;
echo ", ";
echo $pid;
echo " ";
}
?></td></tr>
<input type="submit" value="Save Changes" name="add" >
</form>
</table>
<?php
if(isset($_POST['add']))
{
$chk = $_POST['checkbox'];
$val = explode(",",$chk);
$bn = $val[0];
$cid= $val[1];
$scid= $val[2];
$prid= $val[3];
echo "<script type='text/javascript'>alert('brand: ". $bn."')</script>";
echo "<script type='text/javascript'>alert('cat: ". $cid."')</script>";
echo "<script type='text/javascript'>alert('sub: ". $scid."')</script>";
echo "<script type='text/javascript'>alert('pr: ". $prid."')</script>";
}?>
Use brackets in your checkbox name attribute name="checkbox[]" and your post variable will be an array of selected values.
Edit: I noticed you have form opening tag inside the while loop. You need to put it before while loop otherwise its generating tons of opening form tags.
So it looks like you have only one checkbox. If you want to POST the values of all the checkboxes as an array I believe you need to add [] to the name of your input field. So:
<input type="checkbox" name="checkbox[]" value="<?php echo "$bname";?>"/>
<input type="checkbox" name="checkbox[]" value="<?php echo "$catid";?>"/>
<input type="checkbox" name="checkbox[]" value="<?php echo "$subcatid";?>"/>
<input type="checkbox" name="checkbox[]" value="<?php echo "$pid";?>"/>
Hopefully I understood your question.

Checkboxes are checking out

I've got a page with checkboxes generated with the database. When we press the checkbox and submit it, it is working fine and it is updating in the database. But when I try to uncheck "1" checkbox it is checking out all checkboxes which are selected.
Query:
if(isset($_POST['submit'])){
foreach ($_POST['untrain'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainQuery = "UPDATE room_users SET trained = '1' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainQuery);
}
}
if(isset($_POST['submit'])){
foreach ($_POST['amk'] as $room_id => $user_id) {
// This query needs protection from SQL Injection!
$user_id;
$untrainedQuery = "UPDATE room_users SET trained = '0' WHERE user_id = $user_id AND room_id = $room_id";
$db->update($untrainedQuery);
}
}
Checkboxes:
<?php
if($room->trained == 1)
{ ?>
<input type='hidden' value="<?php echo $room->user_id; ?>" name="amk[<?php echo $room->room_id; ?>]">
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="trained[<?php echo $room->room_id; ?>]" checked>
<?php echo "Y"; }
else{ ?>
<input type='checkbox' value="<?php echo $room->user_id; ?>" name="untrain[<?php echo $room->room_id; ?>]">
<?php echo "N";
}?>
</td>
<Td><?php
if($room->active == 1) {
?> <input type='checkbox' name="<?php echo $room->room_id; ?>" checked>
<?php echo "Active"; }
else { ?>
<input type='checkbox' name="<?php echo $room->room_id; ?>"
<?php echo "Inactive"; } ?>
I used the trick with the "hidden" input before the checkbox, but the only problem is that it is not working. When I click on it, it resets all checkboxes to 0.
I think you are missing how the combo checkbox + hidden input does work.
So here you go freely inspired by this answer:
<input id="foo" name="foo" type="checkbox" value="1" />
<input name="foo" type="hidden" value="0" />
Looks like you do know, if you use the trick, that, if the checkbox is unchecked, it will not be present in the post. So to trick the form, we will always add an hidden field. And if the checkbox is checked, then the fact that it will be included in the post is going to override the value of the hidden input.
So for your specific problem :
<td>
<input type="checkbox" value="1" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]" <?php echo ($room->trained == 1) ? ' checked' : '' ?> /> Trained
<input type="hidden" value="0" name="trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>]"/>
</td>
Please note the use of the ternary operator on this part of the code <?php echo ($room->trained == 1) ? ' checked' : '' ?> which I may use a lot when writing html template.
Please also note the trick on the name trained[<?php echo $room->room_id; ?>_<?php echo $room->user_id; ?>] which is needed because we cannot set the user_id as value of the input.
Then for the processing part :
if ( isset ( $_POST['submit'] ) ) {
foreach ( $_POST['trained'] as $ids => $value ) {
// This query needs protection from SQL Injection!
// ^ good point, on which I would suggest you using PDO and prepared statement :)
list($room_id,$user_id) = explode('_',$ids);
// ^ now need to explode the name on the underscore to get both user_id and room_id cf the trick above
$untrainQuery = "UPDATE room_users SET trained = '$value' WHERE user_id = $user_id AND room_id = $room_id";
$db->update ( $untrainQuery );
}
}
Wash, rinse, repeat for every checkbox you need and you should be good to go.

Set update form checkbox array to 0 instead of NULL

I have a update form that populates from a database dynamically, I have two checkboxes in my form that post to an array so I can hit one submit button and update all rows with a foreach statement. The text fields work as they should, but when the checkbox fields post to their array, they leave out the zeros my arrays become shorter.
How do I add 0 where a null checkbox would be?
this is my form
<form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
<input type="hidden" name="ss_id[]" value="<?php echo $row_rsSnapshot['ss_id']; ?>" />
<input type="hidden" name="ss_yearmonth[]" value="<?php echo htmlentities($row_rsSnapshot['ss_yearmonth'], ENT_COMPAT, 'UTF-8'); ?>" />
<tr>
<td>
<input <?php if (!(strcmp($row_rsSnapshot['ss_inventory'],1))) {echo "checked=\"checked\"";} ?> type="checkbox" name="ss_inventory[]" value="" <?php if (!(strcmp(htmlentities($row_rsSnapshot['ss_inventory'], ENT_COMPAT, 'UTF-8'),""))) {echo "checked=\"checked\"";} ?> />
</td>
<td>
<input <?php if (!(strcmp($row_rsSnapshot['ss_write_off'],1))) {echo "checked=\"checked\"";} ?> type="checkbox" name="ss_write_off[]" value="" <?php if (!(strcmp(htmlentities($row_rsSnapshot['ss_write_off'], ENT_COMPAT, 'UTF-8'),""))) {echo "checked=\"checked\"";} ?>
</td>
<td>
<input type="text" name="ss_date[]" value="<?php echo htmlentities($row_rsSnapshot['ss_date'], ENT_COMPAT, 'UTF-8'); ?>" size="32" />
</td>
<td>
<input type="text" name="ss_transaction[]" value="<?php echo htmlentities($row_rsSnapshot['ss_transaction'], ENT_COMPAT, 'UTF-8'); ?>" size="32" />
</td>...
And here is my sql update query
foreach($_POST['ss_id'] as $key=>$ss_id){
$ss_inventory = GetSQLValueString(isset($_POST['ss_inventory'][$key]) ? "true" : "", "defined","1","0");
$ss_write_off = GetSQLValueString(isset($_POST['ss_write_off'][$key]) ? "true" : "", "defined","1","0");
$ss_date = $_POST['ss_date'][$key];
$ss_transaction = $_POST['ss_transaction'][$key];
$ss_debit = $_POST['ss_debit'][$key];
$ss_credit = $_POST['ss_credit'][$key];
$ss_yearmonth = $_POST['ss_yearmonth'][$key];
$sql = "UPDATE snapshot SET ss_inventory = '$ss_inventory', ss_write_off = '$ss_write_off', ss_date = '$ss_date', ss_transaction = '$ss_transaction', ss_debit = '$ss_debit', ss_credit = '$ss_credit' , ss_yearmonth = '$ss_yearmonth' WHERE ss_id = '$ss_id' ";
mysql_select_db($database_connMyayla, $connMyayla);
$Result1 = mysql_query($sql, $connMyayla) or die(mysql_error());
}
}
mysql_close();
?>
this solved it
If anyone is interested...
I put a counter to find out how many rows are being populated with this query and inserted that into my checkbox name array...
$i = 0;
do {
...
<td>
<input <?php if (!(strcmp($row_rsSnapshot['ss_inventory'],1))) {echo "checked=\"checked\"";} ?> type="checkbox" name="ss_inventory[<?php echo $i;?>]" value="" <?php if (in_array($i, $ss_inventory)) echo "checked='checked'"; ?> />
</td>
<td>
<input <?php if (!(strcmp($row_rsSnapshot['ss_write_off'],1))) {echo "checked=\"checked\"";} ?> type="checkbox" name="ss_write_off[<?php echo $i;?>]" value="" <?php if (in_array($i, $ss_write_off)) echo "checked='checked'"; ?> />
</td>
....
$i++;
} while ($row_rsSnapshot = mysql_fetch_assoc($rsSnapshot));
now the checkboxes that are checked will correspond with the correct array number..
e.g.
lets say you have 4 rows of data, but you only check the checkboxes for row 2 and 4.
//run this to see your result
print_r($_POST['ss_inventory']);
//outputs: Array ([1] => [3] =>)
Before this was my output, everything was pushed up to the start of my array because the false checkboxes were not being submitted or NULL. so rows 1 and 2 would result true.
//outputs: Array ([0] => [1] =>)
Also See
Checkbox "checked"-value jumps up to earlier array values, when array is empty
The browser does not submit unchecked checkboxes. You'll need to either give unique names, or simply use radio buttons.

Categories