Set update form checkbox array to 0 instead of NULL - php

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.

Related

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 />';
}
}
}

radio button in while loop

i am coding a page for the attendance of students and in the page all the students name are retrieved dynamically from database using while loop and inside the while loop i have used a radio button.
my problem is the radio button work's correctly but i am unable to insert the value of radio buttons into database.here is my code :
include'connection.php';
#$id = mysql_real_escape_string($_GET['id']);
$res=mysql_query("SELECT * FROM `std_register` AS p1 ,`sims-register-course` AS p2 WHERE p2.semester=p1.std_semester and p2.department=p1.std_department and p2.id = '".$id."'");
if ($res==FALSE) {
echo die(mysql_error());
}
while ($row=mysql_fetch_assoc($res)) { ?>
<input type="hidden" id="dept_0" name="dept[]" value="<?php echo $row["department"] ?>">
<input type="hidden" id="course_name_1" name="course_name[]" value="<?php echo $row["course_name"] ?>">
<input type="hidden" id="std_semester_2" name="std_semester[]" value="<?php echo $row["semester"] ?>">
<input type="hidden" id="std_id_3" name="std_id[]" value="<?php echo $row["id"] ?>">
<input type="hidden" id="std_name_4" name="std_name[]" value="<?php echo $row["std_name"] ?>">
<tr>
<td class =info><?php echo $row["std_name"];?></td>
<td><input type="radio" name="<?php echo "status['".$row["std_name"]."']" ?>" value="1"></td>
<td><input type="radio" name="<?php echo "status['".$row["std_name"]."']" ?>" value="2"></td>
</tr>
<?php }?>
</table><br>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-3">
<input type="submit" name="submit" value="Assign" class="btn btn-large btn-block btn-primary"></div></div>
</form>
<?php
for ($i=0; $i < 4; $i++) {
if(isset($_POST["submit"])) {
$stdid = mysql_real_escape_string($_POST['std_id'][$i]);
$dptname = mysql_real_escape_string($_POST['dept'][$i]);
$courseName = mysql_real_escape_string($_POST['course_name'][$i]);
$stdSemester = mysql_real_escape_string($_POST['std_semester'][$i]);
$std_name = mysql_real_escape_string($_POST['std_name'][$i]);
$present = mysql_real_escape_string($_POST['status'][$i]);
$totalClasses = $present;
$insrt = mysql_query("INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester','$present',0,0)") or die(mysql_error());
}
}
and is it possible to insert values from this radio buttons to two columns of database?
I am not sure but try to add 'checked' property in radio input
<input type="radio" name="<?php echo "status[".$row["std_name"]."]" ?>" value="1" checked></td>
Or
use Select tag instead of radio button
EDIT
use this code to insert in present column or absent column
$value = mysql_real_escape_string($_POST['status'][$i]);
$totalClasses = $value;
if($value == 1) //check if present
{
$sql="INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester','$value',0,0)";
}
else //if absent
{
$sql="INSERT INTO `attendence_student` (department_name,courseName,semester,present,absent,total_classes) VALUES('$dptname','$courseName','$stdSemester',0,'$value',0)";
}
$insrt = mysql_query($sql) or die(mysql_error());

PHP - Loop number of selected check boxes on form submit

I have an issue where I need to loop the number of check boxes on a form submit. Foreach check box that is looped I need to then insert data into the database.
How Would I go about looping over the amount of check boxes that have being passed via form submit?
My code is as follows:
Form:
<form action="createChallenge.php" method="post" name="chalCreate">
Challenge Name:<input type="text" name="chalName" />
<br />
Challenge Target:<input type="text" name="chalTarget"/>
<br />
End Date:<input type="text" name="chalDate">
<br />
<!-- Needs a jquery datepicker -->
Select Friends: <br />
<?php
$selFriend = $conn->prepare("SELECT * FROM Friends WHERE UserID = '$userID' AND Friend = 'y' ORDER BY FriendName ASC");
$selFriend->execute();
foreach($selFriend as $row){
?>
<input type="checkbox" name="test" value="<?php echo $row['FriendID'] ?>"><?php echo $row['FriendName'] ?><br>
<?php
}
?>
<br />
<button type="submit">Create Challenge</button>
</form>
PHP to handle the form:
<?php
if(isset($_POST['test']))
{
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
echo $name = $_POST['chalName'];
echo $target = $_POST['chalTarget'];
echo $date = $_POST['chalDate'];
echo $friend = $_POST['test'];
echo $setby = $_COOKIE['userID'];
$create = $conn->prepare("INSERT INTO Challenge ( chalSetBy, chalName, chalTarget, chalDate ) VALUES ('$setby', '$name', '$target', '$date') ");
$create->execute();
if($create)
{
echo "Challenge made successfully";
}
else
{
echo "There was a problem";
}
}
?>
I thought doing the following would echo out data, but it didn't, it only selected the last check box:
$i = 0;
foreach($_POST['test'] as $checked)
{
echo $friend = $checked;
$i++;
}
Make an array of your checkbox in HTML page like as below,
<form name="frm" method="post">
<input type="checkbox" value="1" name="test[]">
<input type="checkbox" value="2" name="test[]">
<input type="checkbox" value="3" name="test[]">
<input type="checkbox" value="4" name="test[]">
<input type="checkbox" value="5" name="test[]">
<input type="checkbox" value="6" name="test[]">
<input type="submit">
</form>
<?php
foreach($_POST['test'] as $key=>$value)
{
echo $value."<br>";
}

Simple PHP questions about hiding a input

I want to hide a field of a form when number 1 has been chosen and is loaded in the databse.
The code gives no errors, but the field stays visible with number 0 and 1.
Somehow I can't get it right. It tried the following;
<?php
$query3 = mysql_query("SELECT `status`, `authcode` FROM `auth` ORDER BY `status` ASC LIMIT 1");
while($row3 = mysql_fetch_object($query3)){
?>
<tr>
<td><b>Authcode:</b></td>
<td>
<input name="authcode" type="text" value="<?= $row->authcode; ?>" <?php if($row->status == 0) ?> />
<input name="authcode2" type="hidden" value="<?= $row->authcode; ?>" <?php if($row->status == 1) ?> />
</td>
</tr>
You need to wrap the if around the output you want to be conditionalized on it:
<?php if ($row3->status == 0) { ?>
<input name="authcode" type="text" value="<?= $row3->authcode; ?>" />
<?php }
if ($row3->status == 1) { ?>
<input name="authcode2" type="hidden" value="<?= $row3->authcode; ?>" />
<?php } ?>
You have to put the if statement before:
<?php if ($row->status == 1) ?>
<input name="authcode2" type="hidden" value="<?= $row->authcode; ?>"/>
Agree with Bamar and Pablo.
If you only want the hidden field once (row->status == 1), you could be more precise with something like:
<input name="authcode" type="<?php echo (($row->status == 1)?'hidden':'text') ?>" value="<?php echo $row->authcode; ?>" />
Cheers.

retrieving multiple values from checkbox and hidden field

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/>";
}
}

Categories