Checkbox is not giving Any value after checked in - php

I'm trying to edit my selections using checkbox method, the values which are previously in database are checked while the other's are not. What I'm trying to do is check other checkbox or uncheck the previous selected check box but when i submit my edition nothing got happen because It is not getting values from the checkboxes I don't know why. Here is my Code. Thank you
<?php
if(isset($_GET['Institute_Code']))
{
$Institute_Code=$_GET['Institute_Code'];
$getselect=mysqli_query($con,"SELECT radio FROM institute WHERE Institute_Code='$Institute_Code'");
while($row=mysqli_fetch_array($getselect))
{ $Degree_Programs = $row ['radio'];
}}
?>
<form action="#" method="post" name="add_Institute">
<div class="container">
<!--add here-->
<?php
$char="";
$name[]="";
$j=0;
$dbvalue="";
if($Degree_Programs!=NULL )
{
$Degree_ProgramStrlen=Strlen($Degree_Programs);
for ($i=0; $i<=$Degree_ProgramStrlen; $i++)
{
$char = substr( $Degree_Programs, $i, 1 );
if($char == ',')
{
//echo $name[$j];
//$name="";
$j=$j+1;
$name[$j]="";
}
else
{
$name[$j] .= $char;
}
}
}
else
{} ?>
<!--" >-->
<div class="row col-md-offset-1">
<div class="col-md-9 ">
<?php echo "<b>Degree Programs</b>"; ?>
<br>
<?php for($i=0;$i<count($name)-1;$i++)
{ if($name[$i]=='Matric Arts')
$dbvalue=$name[$i];
} ?>
<label>Matric Arts</label>
<input type="checkbox" name="check_DegreePrograms[]" value="Matric Arts" <?php
$value="Matric Arts";
echo ( $dbvalue==$value ? 'checked' : '');?>>
<?php for($i=0;$i<count($name)-1;$i++)
{ if($name[$i]=='Matric Science')
$dbvalue=$name[$i];
} ?>
<label for="tag_2">Matric Science</label>
<input type="checkbox" name="check_DegreePrograms[]" id="tag_2" value="Matric Science" <?php
$value="Matric Science";
echo ( $dbvalue==$value ? 'checked' : '');?>>
<?php for($i=0;$i<count($name)-1;$i++)
{ if($name[$i]=='FSc. Pre-Engineering')
$dbvalue=$name[$i];
} ?>
<label for="tag_3">FSc. Pre-Engineering</label>
<input type="checkbox" name="check_DegreePrograms[]" id="tag_3" value="FSc. Pre-Engineering" <?php
$value="FSc. Pre-Engineering";
echo ( $dbvalue==$value ? 'checked' : '');?>>
<?php for($i=0;$i<count($name)-1;$i++)
{ if($name[$i]=='Fsc. Pre-Medical')
$dbvalue=$name[$i];
} ?>
<label for="tag_4">FSc. Pre-Medical</label>
<input type="checkbox" name="check_DegreePrograms[]" id="tag_4" value="FSc. Pre-Medical"<?php
$value="FSc. Pre-Medical";
echo ( $dbvalue==$value ? 'checked' : '');?>>
<?php for($i=0;$i<count($name)-1;$i++)
{ if($name[$i]=='I.com')
$dbvalue=$name[$i];
} ?>
</div>
</div>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success pull-right"/>
</form>
</div>
<?php //} }
$pets ="";
$flag =0;
if(isset($_GET['Institute_Code']))
{
$Institute_Code=$_GET['Institute_Code'];
if (isset($_POST['Submit'])) {
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_DegreePrograms'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_DegreePrograms'] as $selected){
$pets .= $selected . ",";
$flag = 1;
}
}
}
if ($flag == 1) {
$pets = rtrim($pets);
}
$updated = mysqli_query($con ,"UPDATE institute set radio='$pets' where Institute_Code=1233");
if($updated)
{
echo "Data successfully updated...";
}
else {
die('Could not update data: ' . mysql_error());
}
}
}
?>
<?php
include 'footer.php';
?>'

Related

Populating checkboxes from database using PHP - only last option is getting checked

I am trying to populate checkboxes with the data from my mysql database but for some reason only the last checkbox is being checked (for example if automotive, carpentry and hand tools should be checked, only hand tools is being checked) and I can't figure out why. The mysql statement is running correctly and giving me the correct information. Here is the relevant code.
<?php
require_once('../../private/initialize.php');
require_login();
if(!isset($_GET['id'])) {
redirect_to(url_for('/members/show_member_tools.php'));
}
$id = $_GET['id'];
if(is_post_request()) {
// Handle form values sent by new.php
$tool = [];
$tool['tool_ID'] = $id;
$tool['serial_number'] = $_POST['serial_number'] ?? '';
$tool['tool_name'] = $_POST['tool_name'] ?? '';
$tool['tool_description'] = $_POST['tool_description'] ?? '';
$tool['tool_picture'] = $_POST['tool_picture'] ?? '';
$category =[];
$category = $_POST['category_ID'];
$result = update_tool($tool, $category);
//get info for checkboxes
global $db;
if($result === true) {
$_SESSION['message'] = "The tool has been updated sucessfully";
redirect_to(url_for('/members/show_tool.php?id=' . $id));
} else {
$errors = $result;
}
} else {
$tool = find_tool_by_id($id);
if(isset($_GET['id'])){
$id=$_GET['id'];
$sql = "select category_name from category INNER JOIN tool_category ON category.category_ID = tool_category.category_ID where tool_category.tool_id=$id";
$query = mysqli_query($db, $sql);
while($row=mysqli_fetch_array($query)) {
// $str = "";
$str = $row['category_name'];
echo $str;
if (strpos($str , "automotive")!== false){
$checked1 ="checked";
echo "made it to automotive";
} else {
$checked1 ="";
}
if (strpos($str , "carpentry")!== false){
$checked2 ="checked";
echo "made it to carpentry";
} else {
$checked2 ="";
}
if (strpos($str , "home maintenance")!== false){
$checked3 ="checked";
echo "made it to home maintenance";
} else {
$checked3 ="";
}
if (strpos($str , "plumbing")!== false){
$checked4 ="checked";
} else {
$checked4 ="";
}
if (strpos($str , "yard and garden")!== false){
$checked5 ="checked";
} else {
$checked5 ="";
}
if (strpos($str , "hand tools")!== false){
$checked6 ="checked";
} else {
$checked6 ="";
}
}//end while loop
} //end if
} //end else
$tool_set = find_all_tools();
$tool_count = mysqli_num_rows($tool_set);
mysqli_free_result($tool_set);
?>
<?php $page_title = 'Edit Tool'; ?>
<?php include(SHARED_PATH . '/header.php'); ?>
<div id="content">
<div class="center">
« Back to My Tools
<h2>Edit Tool</h2>
</div>
<?php echo display_errors($errors); ?>
<form action="<?php echo url_for('/members/edit_tool.php?id=' . h(u($id))); ?>" method="post">
<fieldset class="form">
<img src ="<?php echo h($tool['tool_picture']); ?>" alt="<?php echo h($tool['tool_picture']); ?>"width="150"><br>
<label for="serial_number">Serial Number</label><br>
<input type="text" name="serial_number" value="<?php echo h($tool['serial_number']); ?>" ><br>
<label for="tool_name">Tool Name</label><br>
<input type="text" name="tool_name" value="<?php echo h($tool['tool_name']); ?>" ><br>
<label for="tool_description">Tool Description</label><br>
<input type="text" name="tool_description" value="<?php echo h($tool['tool_description']); ?>" ><br>
<label for="category_ID">Tool Category: </label><br>
<input type="checkbox" name="category_ID[]" value="1" <?php echo $checked1; ?>> <label for="1">Automotive</label> <br>
<input type="checkbox" name="category_ID[]" value="2" <?php echo $checked2; ?>> <label for="2">Carpentry</label> <br>
<input type="checkbox" name="category_ID[]" value="3" <?php echo $checked3; ?>> <label for="3">Home Maintenance</label> <br>
<input type="checkbox" name="category_ID[]" value="4" <?php echo $checked4; ?>> <label for="4">Plumbing </label><br>
<input type="checkbox" name="category_ID[]" value="5" <?php echo $checked5; ?>> <label for="5">Yard and Garden</label> <br>
<input type="checkbox" name="category_ID[]" value="6" <?php echo $checked6; ?>> <label for="6">Hand Tools</label> <br>
<input type="submit" value="Edit Tool" >
<a class="block" href="<?php echo url_for('/members/delete_tool.php?id=' . $id); ?>">Delete Tool</a>
</fieldset>
</form>
<div class="push"></div>
</div>
<?php include(SHARED_PATH . '/footer.php'); ?>
You're looping over your results. This means with every loop you're setting one variable to "checked" and the rest to an empty string. So only the last one will be checked. The band-aid fix is to set unchecked as the default outside of the loop, and then change to checked only when it's needed.
But the real fix is to be pulling this info from the database and working with it instead of manually mapping database IDs to labels. By moving your condition into the join, you pull all the categories. The rows that have a tool ID are checked, and the others are not. You're also pulling the category names and IDs so you can programmatically build your checkboxes.
See here for DB sample: http://sqlfiddle.com/#!9/20b223/14/0
$tool = find_tool_by_id($id);
$tool["categories"] = [];
$sql = "SELECT c.category_name, c.category_ID, tc.tool_id
FROM category c
LEFT JOIN tool_category tc ON c.category_ID = tc.category_id
AND tc.tool_id = ?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i", $_GET["id"]);
$result = $stmt->execute();
while($row = $stmt->fetch_assoc()) {
$id = $row["category_ID"];
$name = $row["category_name"];
$checked = $row["tool_id"] ? "checked" : "";
$tool["categories"][$id] = ["name" => $name, "checked" => $checked];
}
Now later on you can do this to automatically build all your checkbox inputs:
<?php foreach ($tool["categories"] as $id=>$category): ?>
<input type="checkbox" name="category_ID[]" id="category_<?=$id?>" value="<?=$id?>" <?=$category["checked"]?>>
<label for="category_<?=$id?>">
<?=htmlspecialchars($category["name"])?>
</label><br/>
<?php endforeach ?>

How to show a php radio input value on a php email?

I have a php form with 4 radio inputs as below:
<?php if( $chauffeur_data['enable-paypal'] == '1' ) { ?>
<div class="radio-wrapper clearfix"><input type="radio" name="payment-method" value="paypal" <?php if( $paypal_check == '1' ) { echo 'checked="checked"'; } ?> /><label><?php esc_html_e('Pay with PayPal','chauffeur'); ?></label><img src="<?php echo plugins_url('../../assets/images/paypal.png', __FILE__); ?>"></div>
<?php } ?>
<?php if( $chauffeur_data['enable-stripe'] == '1' ) { ?>
<div class="radio-wrapper clearfix"><input type="radio" name="payment-method" value="stripe" <?php if( $stripe_check == '1' ) { echo 'checked="checked"'; } ?> /><label><?php esc_html_e('Pay with Credit Card','chauffeur'); ?></label><img src="<?php echo plugins_url('../../assets/images/stripe.png', __FILE__); ?>"></div>
<?php } ?>
<?php if( $chauffeur_data['enable-cash'] == '1' ) { ?>
<div class="radio-wrapper clearfix"><input type="radio" name="payment-method" value="cash" <?php if( $cash_check == '1' ) { echo 'checked="checked"'; } ?> /><label><?php esc_html_e('Pay with Cash to the Driver','chauffeur'); ?></label></div>
<?php } ?>
<?php if( $chauffeur_data['enable-pos'] == '1' ) { ?>
<div class="radio-wrapper clearfix"><input type="radio" name="payment-method" value="pos" <?php if( $pos_check == '1' ) { echo 'checked="checked"'; } ?> /><label><?php esc_html_e('Pay with Card on POS in the Car','chauffeur'); ?></label></div>
<?php } ?>
<?php // If all payment gateways are disabled
if( $chauffeur_data['enable-paypal'] != '1' && $chauffeur_data['enable-stripe'] != '1' && $chauffeur_data['enable-cash'] != '1' &&
$chauffeur_data['enable-pos'] != '1' ) { ?>
<input type="hidden" name="payment-method" value="cash" />
<?php } ?>
<button name="pay_now" id="pay_now" class="payment-button" type="submit">
<?php esc_html_e('Proceed To Payment','chauffeur'); ?>
</button>
<?php } else { ?>
<input type="hidden" name="payment-method" value="cash" />
<button name="pay_now" id="pay_now" class="payment-button" type="submit">
<?php esc_html_e('Proceed To Book','chauffeur'); ?>
</button>
<?php } ?>
When one of the radio buttons is checked, how can I show its value (e.g. pos) to the email I send?
The email is like below. What should be my code to show the radio button choice?
$customer_email_content .= '<li><strong>' . esc_html__('Payment Method you Selected','chauffeur') . ': </strong>' . '**payment-method-goes-here**' . '</li>'."\r\n";
After form is submitted, get the radio button value from $_POST array;
$payment_method = $_POST['payment-method'];
Use $payment_method to show the value of the radio button that is selected.
$customer_email_content .= '<li><strong>' . esc_html__('Payment Method you Selected','chauffeur') . ': </strong>' . $payment_method . '</li>'."\r\n";

validate if checkbox has been checked

I'm trying to show an error message if a checkbox has not been selected. I've managed to get it done input field, but unsure of how to get it done with a checkbox. This is what I have so far:
<?php
# check if data has been posted
if (!empty($_POST)) {
# keep track validation errors
$author_error = null;
$categories_error = null;
# keep track of post values
$author = $_POST['author'];
$categories = $_POST['categories'];
# validate input
if (empty($author)) {
$author_error = 'Please select author';
$valid = false;
}
if (empty($categories)) {
$categories = 'Please select categories';
$valid = false;
}
# if data is valid, insert into the database
if ($valid) {
}
}
?>
<div class="control-group <?php if (!empty($author_error)){ echo 'error'; } ?>">
<label class="control-label">Author</label>
<div class="controls">
<select name="author" id="author">
<option value="">Select one</option>
<?php $sql2 = 'SELECT id, name FROM author';
foreach ($dbConnection->query($sql2) as $data2) { ?>
<option value="<?php echo $data2['id']; ?>"
<?php if(isset($author) && $author == $data2['id']) { echo 'selected'; } ?>>
<?php echo $data2['name']; ?>
</option>
<?php } ?>
</select>
<?php if (!empty($author_error)) { echo '<span class="help-inline">' . $author_error . '</span>'; } ?>
</div>
</div>
<div class="control-group <?php if (!empty($categories_error)){ echo 'error'; } ?>">
<fieldset>
<legend class="control-label">Categories:</legend>
<?php $sql3 = 'SELECT id, name FROM category';
foreach ($dbConnection->query($sql3) as $data3) { ?>
<div class="controls">
<label for="category<?php echo($data3['id']);?>">
<input type="checkbox" name="categories" id="categories" value="<?php echo($data3['id']); ?>"
<?php if(isset($_POST['categories']) && in_array($data3['id'], $_POST['categories'])) { echo 'checked'; } ?>>
<?php echo($data3['name']); ?>
</label>
</div>
<?php } ?>
</fieldset>
<?php if (!empty($categories_error)) { echo '<span class="help-inline controls">' . $categories_error . '</span>'; } ?>
</div>
Where am I going wrong with the categories field?
Check it like:
isset($_POST['categories'])
On line #62 you are checking if $categories_error is empty but you are using variable $categories for storing error message on line #19

if statement is equal to a value

I have a result(string) of 1,1,0,0 - These come from $sub_array['state']
Currently all of my check boxes are checked. How can I code the code below so that if its 1 its checked else its not? as the current code gives them all 'checked'
<?php
foreach($assoc_categories as $sub_array)
{
if($sub_array['state'] == 1)
{
$checked_state = " checked='checked'";
}
?>
<div>
<input
class="checkbox"
type="checkbox"
name="product_category"
class="product_category_selector"
id="product_category_<?php echo $sub_array['cat_id']; ?>"
data-id="<?php echo $sub_array['cat_id']; ?>"
<?php echo $checked_state; ?>
/>
<?php echo $sub_array['name']; ?>
</div>
<input
class="order"
type="input"
value="<?php echo $sub_array['sorder']; ?>"
/>
<?php
}
?>
Change:
if($sub_array['state'] == 1)
{
$checked_state = " checked='checked'";
}
To:
if($sub_array['state'] == 1)
{
$checked_state = " checked='checked'";
} else
{
$checked_state = "";
}
Basically, you are not clearing the previous value as the loop continues.
Alternatively, you could use:
$checked_state = ($sub_array['state'] == 1) ? " checked='checked'" : "" ;
You forget to reset checked_state or reset it to '' if $sub_array['state'] is equal to 0.
<?php
$assoc_categories = array(
array('state'=>1, 'cat_id'=>1, 'name'=>'one', 'sorder'=>1),
array('state'=>1, 'cat_id'=>2, 'name'=>'three', 'sorder'=>2),
array('state'=>0, 'cat_id'=>3, 'name'=>'four', 'sorder'=>3),
array('state'=>0, 'cat_id'=>4, 'name'=>'five', 'sorder'=>4),
);
foreach($assoc_categories as $sub_array)
{
$checked_state = $sub_array['state'] == 1 ? " checked='checked'" : '';
?>
<div>
<input
class="checkbox"
type="checkbox"
name="product_category"
class="product_category_selector"
id="product_category_<?php echo $sub_array['cat_id']; ?>"
data-id="<?php echo $sub_array['cat_id']; ?>"
<?php echo $checked_state; ?>
/>
<?php echo $sub_array['name']; ?>
</div>
<input
class="order"
type="input"
value="<?php echo $sub_array['sorder']; ?>"
/>
<?php
}

html form does not work inside fieldsets

I have a field set and inside it i have a form . it does not work . i mean to say . when i see the tags using firebug , the form tags will not be there at all..how do u i get over it.
this is how the code goes...its a php code..
<div id="dialog-form_surg_couns" title=" Surgical Counselling">
<?php
$surgCount = 0;
foreach($this->surgery as $surgery) {
$surgCount++;
$newId = str_replace(' ','',$surgery->getSurgeryname());
?>
<div class='fieldreq1Pct'>
<div class='fieldItemLabel'>
<label for=''><?php echo $surgery->getSurgeryname() ?></label>
</div>
<div class='fieldItemValue'>
<input type='checkbox' class='surg_couns_tests' id="<?php echo $newId ?>" name='surg_couns_tests' value="<?php echo $surgery->getSurgeryname() ?>" <?php echo (($showValue && strstr($visitRecord->getSurgcounstests(),$surgery->getSurgeryname())) ? 'checked' : "" ); ?> onClick="javascript:showBlock(this.id);">
</div>
</div>
<?php
if(($surgCount % 3) == 0)
{
?>
<div class='clear'></div>
<?php
}
}
?>
<div class='clear'></div>
<hr/>
<?php
foreach($this->surgery as $surgery) {
$newId = str_replace(' ','',$surgery->getSurgeryname());
$fieldCount = 0;
?>
<div id='<?php echo $newId ?>_block' style='display:none;' class='check_block'>
<form method='POST' action ='' id ='<?php echo $newId ?>_form'>
<table border='0' class='surg_table'>
<?php
foreach($this->surgeryTemplate as $surgerytemplate) {
if($surgery->getSurgeryid() == $surgerytemplate->getSurgeryid())
{
$fieldCount++;
$fieldName = 'field'.$fieldCount;
$fieldId = $surgerytemplate->getFieldid();
if($surgerytemplate->getRequired() == 'Y')
{
$required = 'required';
}
else
{
$required = '';
}
if($surgerytemplate->getType() == 'AN')
{
$validation = 'alpha';
}
else
{
$validation = '';
}
?>
<tr>
<td>
<?php echo $surgerytemplate->getFieldname(); ?>
</td>
<td>
<?php
if($surgerytemplate->getType() == 'B')
{
echo '<input type=\'radio\' name=\''.$fieldName.'\' value=\'Yes\'>Yes';
echo '<input type=\'radio\' name=\''.$fieldName.'\' value=\'No\'>No';
}
else
{
echo '<input type=\'text\' name=\''.$fieldName.'\' id=\''.$fieldName.'\' class=\''.$required.' '.$validation.'\' onblur="checkValid(this.id)"><div id=\''.$fieldName.'error\'></div>';
}
?>
</td>
</tr>
<?php
}
}
?>
</table>
<center><input type='button' name='submit' value='submit' onclick='javascript:submitSurgeryForm("<?php echo $newId ?>")'></center>
</form>
</div>
<?php
}
?>
</div>
You can't have a form tag inside another form. The following HTML is invalid:
<form>
<fieldset>
<form>
<input>
</form>
</fieldset>
</form>
The browser will silently ignore the second form, and instead will interpret your page as:
<form>
<fieldset>
<input>
</fieldset>
</form>

Categories