Retain Checked the checkbox inside While - php

this code is inside while after I submit the form instead of retaining what I checked it checked all after submitting.
I just want to happen after submitting the only check box i check is checked.
What should i do ?
<input type="checkbox" title ="<?php echo $sym ?>"<?php if(isset($_POST['poscon'])) echo "checked='checked'"; ?> name="poscon[]" value ="<?php echo $pc?>"><?php echo $pc?>

refer to in_array
<?php
if(isset($_GET["poscon"])) {
$_SESSION["poscon"] = $_GET["poscon"];
$dr=$_SESSION['poscon'];
if(isset($_POST['submit'])) {
if(!empty($_GET['poscon']))
$_SESSION['poscon'] = $_POST['poscon'];
$part=$_GET["poscon"];
}
$poscon=mysqli_real_escape_string($link,$_GET['poscon']);
$p = mysqli_query($link,"select distinct PossibleCondition,Symptoms from healthguide where Subpart like '%$poscon%' and PossibleCondition REGEXP '^[N-Z].*$' Order by PossibleCondition ");
while($r=mysqli_fetch_array($p)) {
$pc=$r["PossibleCondition"];
$sym=$r["Symptoms"];
if(isset($_POST) && isset($_POST['poscon']) && in_array($pc,$_POST['poscon']))
$strIsChecked='checked="checked"';
else
$strIsChecked=null;
echo '<tr>';
echo '<td><input type="checkbox" '.$strIsChecked.' title ="'.$sym.'" name="poscon[]" value ="'.$pc.'"></td>';
echo '<td>'.$pc.'</td>';
echo '</tr>';
}
}
?>

$_POST['poscon'] is a array. Run my script and see how it works.
<?php
/**
* File test.php
*/
// Store checked Values in Array $arrChecked
$arrChecked=array();
if(isset($_POST) && $_POST['poscon']) {
// Debug: Show all POST Vars
echo "<pre>"; print_r($_POST); echo "</pre>";
foreach($_POST['poscon'] AS $checkboxValue) {
// fill array with checked values
// e.g. arrChecked['foo'] = true;
$arrChecked[$checkboxValue] = true;
}
}
/**
* Note for HTML-Block:
* shorthand php if/else used
* http://stackoverflow.com/questions/4567292/overview-of-php-shorthand
*/
?>
<form action="test.php" method="post">
<input type="checkbox" name="poscon[]" value="foo" <?php echo (isset($arrChecked) && $arrChecked['foo'] ? 'checked="checked"' : '');?>> foo
<input type="checkbox" name="poscon[]" value="bar" <?php echo (isset($arrChecked) && $arrChecked['bar'] ? 'checked="checked"' : '');?>> bar
<input type="submit" value="go">
</form>

Related

Problems when using nested foreach on checkboxes loaded dynamically

I need to use nested foreach for dependent checkboxes.
<input type="checkbox" name="all[]" value="<?php echo $row_bus_details['busid'];?>" >
<?php
$book_side_result = mysqli_query($db,"select * from advt_sides");
while($book_side_row=mysqli_fetch_array($book_side_result))
{
?>
<input type="checkbox" name="bookingside[]" value="<?php echo $book_side_row['advt_side_id']; ?>" id="<?php echo $book_side_row['advt_side']; ?><?php echo $row_bus_details['busid'];?>" > <?php echo $book_side_row['advt_side']; ?><br/>
<?php } ?>
I need to loop the selected values of second checkbox if the first checkbox is selected.
I wrote the code like
$i = 0;
$busid = isset($_POST['all']) ? $_POST['all'] : array();
foreach ((array)$busid as $item) {
if(!empty($_POST['bookingside'])) {
foreach($_POST['bookingside'] as $side) {
$sql_book_side=mysqli_query($db,"INSERT INTO `advt_book_side`(bus_id,sides_id) VALUES ('$item','$side')");
$i++;
}
}
}
The result I need is just like the image below
You need to save data in serialize array from in data base like:
$sql_book_side=mysqli_query($db,"INSERT INTO advt_book_side(bus_id,sides_id) VALUES ('$item',serialize(array('left'=>1,'right'=>1,'back'=>0)))");
Print check box with check uncheck using below code
$book_side_result = mysqli_query($db,"select * from advt_sides");
while($book_side_row=mysqli_fetch_array($book_side_result))
{
$array = unserialize($book_side_row['sides_id']);
foreach($array[0] as $side){
?>
<input type="checkbox" name="bookingside[]" value="<?php echo ($side)? $side:0; ?>">
<?php }
} ?>

How to show checkboxes as checked when values are set in the database in codeigniter

I use foreach to show data came from database.
This is for Plan_data
<?php foreach ($veddingPlanData as $row) { ?>
<input box with value containing "echo row->value_name" >
<?php } ?>
This is for task data as check box [here I want to show the checkbox list in which the task is given to plan_id they appear as cheeked checkbox and remaining list with not checked status)
<?php foreach ($veddingPlanTaskMappingData as $row) { ?>
<input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" checked><?php echo $row->task_name?><br>
<?php } ?>
Here I show the whole task list in check box.
<?php foreach ($allVedingTasks as $row) { ?>
<input type="checkbox" name="task_id" value="<?php echo $row->task_id ;?>" ><?php echo $row->task_name?><br>
<?php } ?>
I want to foreach the task_name list with selected some task as there mapped plan_id.
Finally I found It
<?php
$arrSelVedTask = array();
foreach ($veddingPlanTaskMappingData as $row) {
$arrSelVedTask[$row->task_id] = '';
}
?>
<div class="form-group">
<lable for="task_id" class="control-label col-sm-12">Plan Task LIST:</lable>
<div class="col-sm-10">
<div class="checkbox" style="margin-left:40px;">
<?php foreach ($allVedingTasks as $row) {
if(isset($arrSelVedTask[$row->task_id])) {
?><input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" checked ><?php echo $row->task_name; ?><br><?php
}
else{
?><input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" ><?php echo $row->task_name; ?><br><?php
}
}
?>
Simply add a check:
<?php
foreach ($veddingPlanTaskMappingData as $row) {
$checked = ($row->task_id == YOUR_CONDITION) ? 'checked="checked"' : '';
?>
<input type="checkbox" name="task_id[]" value="<?php echo $row->task_id ;?>" <?php echo $checked?>><?php echo $row->task_name?><br>
<?php } ?>
Use set_checkbox Of CI
<input type="checkbox" name="task_id" value="<?php echo $row->task_id ;?>" <?php echo set_checkbox('task_id', $row->task_id); ?> ><?php echo $row->task_name?>
at first in your model fetch the value of checkbox which is in your database then call that function in controller and pass the value to view page. then use if statement with every checkbox item to check whether the value is same or not. and write echo "checked";command if the condition match.
First of all we will take all the categories than we are taking an Id and using it for showing the checked list from the database. First we select the table values based on Id than we will fetch the record. We are having the data in the database column using , comma like 1,2,3,5,9. Than we save it in array and at last we just show that array to the page.
$table="select * from categorytable";
$this->result=mysqli_query($this->con,$table);
$this->count=mysqli_num_rows($this->result);
if($this->count < 1)
{
return "<div class='form-group'>".$messages->getResponseMessage("No category is added.", "Warning")."</div>";
}
else
{
$alert='';
$select="select Category from table where Id='$id'";
$result= mysqli_query($this->con, $select);
$amrow= mysqli_fetch_array($result);
$getAminity=$amrow["Category"];
$getArray= explode(",",$getAminity);
while($row= mysqli_fetch_array($this->result))
{
if(in_array($row[Id],$getArray)){
$alert.="<div class=col-md-2><label class='checkbox-inline'><input type=checkbox id='catval[]' checked name='catval[]' value='$row[Id]'/> $row[Name]</label></div>";
}
else
{
$alert.="<div class=col-md-2><label class='checkbox-inline'><input type=checkbox id='catval[]' name='catval[]' value='$row[Id]'/> $row[Name]</label></div>";
}
}

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.

PHP session echo checkbox and radio buttons

I am trying to echo checkbox names, however I am unable to echo the name of the checkbox as all that appears is a '1' if the checkbox or radio button has been checked.
Does anyone know how I can change my code so that if the user selects that they are a vegetarian and allergic to peanut, "Vegetarian, Peanut Allergy" is displayed on my page instead of the number "1" for each checked item.
I would also prefer the cost of sitting in the VIP area to be echoed as apposed to "Yes" or "No".
Here is my the relevant code for the checkboxes and radio buttons on my reservations page:
<?php
session_start();
if (isset($_POST['submit'])) {
$_SESSION['vege'] = isset($_POST['vege']);
}
if (isset($_POST['submit'])) {
$_SESSION['vegan'] = isset($_POST['vegan']);
}
if (isset($_POST['submit'])) {
$_SESSION['peanut'] = isset($_POST['peanut']);
}
if (isset($_POST['submit'])) {
$_SESSION['gluten'] = isset($_POST['gluten']);
}
if (isset($_POST['submit'])) {
$_SESSION['vip'] = isset($_POST['vip']);
}
?>
...
<strong>Dietary Requirements:</strong>
Vegetarian <input type="checkbox" name="vege" value="Vegetarian" <?php if(isset($_POST['vege'])) echo "checked='checked'"; ?>>
Vegan <input type="checkbox" name="vegan" value="Vegan" <?php if(isset($_POST['vegan'])) echo "checked='checked'"; ?>>
Peanut Allergy <input type="checkbox" name="peanut" value="Peanut Allergy" <?php if(isset($_POST['peanut'])) echo "checked='checked'"; ?>>
Gluten Allergy <input type="checkbox" name="gluten" value="Gluten Allergy" <?php if(isset($_POST['gluten'])) echo "checked='checked'"; ?>>
<strong> VIP area* : </strong> <br><br>
Yes (+£5) <input type="radio" name="vip" <?php if (isset($vip) && $vip=="Yes") echo "checked";?> value="Yes">
<br><span id="vip" class="error"><?php echo $vipErr;?></span><br>
No <input type="radio" name="vip" <?php if (isset($vip) && $vip=="No") echo "checked";?> value="No">
Here is the php I am currently using which echos "1" when the user makes a selection on my thank you page:
<b>Dietary Requirements: </b><?php echo $_SESSION['vege'];?><?php echo $_SESSION['vegan'];?><?php echo $_SESSION['peanut'];?><?php echo $_SESSION['gluten'];?>
<b>VIP Area Costs: </b>£<?php echo $_SESSION['vip'];?>
You assigned not the value to the session array! Because you used isset() as a assignment! And then you assigned 1 because isset returned 1, because they are set!
So try this:
<?php
session_start();
if ( !empty($_POST['vege']) )
$_SESSION['vege'] = $_POST['vege'];
if ( !empty($_POST['vegan']))
$_SESSION['vegan'] = $_POST['vegan'];
if ( !empty($_POST['peanut']))
$_SESSION['peanut'] = $_POST['peanut'];
if ( !empty($_POST['gluten']))
$_SESSION['gluten'] = $_POST['gluten'];
if ( !empty($_POST['vip']))
$_SESSION['vip'] = $_POST['vip'];
?>
Edit:
If you echo session index check if they are set like this:
<b>Dietary Requirements: </b>
<?php
if(isset($_SESSION['vege']))
echo $_SESSION['vege'];
if(isset($_SESSION['vegan']))
echo $_SESSION['vegan'];
if(isset($_SESSION['peanut']))
echo $_SESSION['peanut'];
if(isset($_SESSION['gluten']))
echo $_SESSION['gluten'];
?>
<b>VIP Area Costs: </b>£<?php if(isset($_SESSION['vip'])) echo $_SESSION['vip'];?>
Basically your error is displaying boolean from isset() function.
if you want to echo value just use
$_SESSION['vegan'] = isset($_POST['vegan']) ? $_POST['vegan']:"";
what does the code mean?
$x = $trueOrFalse ? $valueIfTrue : $valueIfFalse;
of course perform some sanitizing:
$_SESSION['vegan'] = htmlspecialchars($_POST['vegan']);
NEVER EVER ECHO PURE USER INPUT! Always sanitize! By not sanitizing user input you allow custom external scripts to easily be run as any HTML tag can be injected into the page such as <script>
Why are you checking your POST['submit'] variable 5 times?
You only need to check it once.
if (isset($_POST['submit'])) {
$_SESSION['vege'] = isset($_POST['vege']) ? $_POST['vege'];
$_SESSION['vegan'] = isset($_POST['vegan']) ? $_POST['vegan'];
$_SESSION['peanut'] = isset($_POST['peanut']) ? $_POST['peanut'];
$_SESSION['gluten'] = isset($_POST['gluten']) ? $_POST['gluten'];
$_SESSION['vip'] = isset($_POST['vip']) ? $_POST['vip'];
}

PHP get checkbox value in checked/unchecked [duplicate]

This question already has answers here:
Get checked and unchecked checkboxes value
(3 answers)
Closed 8 years ago.
<?php
// $groups is fetch_array from mysql
foreach($groups as $group) {
if ($group['delete_user'] === 'Y') {
$checked = "checked=\"checked\";
}
else {
$checked = '';
}
?>
<input type = "checkbox" name="delete_user[<?php echo $group['id']; ?>]" <?php echo $checked; ?>>
<?php
}
?>
Will output:
<form action="test.php" method="post">
<input type="checkbox" name="delete_user[1]">
<input type="checkbox" name="delete_user[2]">
<input type="checkbox" name="delete_user[3]">
<input type="checkbox" name="delete_user[4]" checked="checked">
<input type="submit" name="save_action" value="Save">
</form>
And when I check inputs as wanted, then this will process input.
<?php
if(isset($_POST['save_action']) {
if (empty($_POST['delete_user'])) {
$_POST['delete_user'] = array();
}
foreach($_POST['delete_user'] as $del) {
is_checked($del); //#todo
}
}
?>
I am looking for way to check if check-box is checked and return proper value ( Y or N ). In this point I declared is_checked() function for this purpose.
I would do it like this:
<form action="test.php" method="post">
<input type="checkbox" name="delete_user[]" value="1">
<input type="checkbox" name="delete_user[]" value="2">
<input type="checkbox" name="delete_user[]" value="3">
<input type="checkbox" name="delete_user[]" value="4" checked="checked">
<input type="submit" name="save_action" value="Save">
</form>
Now in PHP you can loop over the $_POST['delete_user'] and it will contain the values of the selected items.
foreach($_POST['delete_user'] as $item)
{
// code to delete $item
}
As the comments already mentioned, only the checked checkboxes will be set
So you either have to take the index as ID or add a val to each input element.
The latter would probably be cleaner (in my opinion)
<?php
// $groups is fetch_array from mysql
foreach($groups as $group) {
if ($group['delete_user'] === 'Y') {
$checked = "checked=\"checked\";
}
else {
$checked = '';
}
?>
<input type = "checkbox" name="delete_user[]" <?php echo $checked; ?> value="<?php echo $group['id'];?>">
<?php
}
?>
And the code which does something with the inputs:
<?php
if(isset($_POST['save_action']) {
if (empty($_POST['delete_user'])) {
$_POST['delete_user'] = array();
}
foreach($_POST['delete_user'] as $del) {
// do something with $del - the id
}
}
?>
Use the checkbox name just as an array and then give the id as value. See the below code.
<?php
// $groups is fetch_array from mysql
foreach($groups as $group) {
if ($group['delete_user'] === 'Y') {
$checked = "checked=\"checked\";
}
else {
$checked = '';
}
?>
<input type = "checkbox" name="delete_user[]" value="<?php echo $group['id']; ?>" <?php echo $checked; ?>>
<?php
}
?>
Then on the action page place this code
<?php
foreach($_POST['delete_user'] as $del) {
is_checked($del); //#todo
}
}
?>
This will work fine.

Categories