PHP function problem - php

I have a php function script that is supposed to uncheck a checkbox or checkboxes if a user unchecks it when the preview button is clicked but I can only get the last
checkbox that was unchecked to stay unchecked but not the other checkeboxes how can I fix this so that all the checkboxes that where unchecked stay unchecked?
Here is part of my PHP function that is giving me the problem.
if(isset($_POST['preview'])){
foreach($query_cat_id as $qci) {
if(!in_array($qci, $cat_id)){
$unchecked = $purifier->purify(strip_tags($qci));
}
}
}
for ($x = 0; $x < count($query_cat_id); $x++){
if(($query_cat_id[$x] == $cat['id']) && ($cat['id'] != $delete_id) && ($cat['id'] != $unchecked)){
echo 'checked="checked"';
}
}

Why not just just check if the variable is set, if the checkbox is checked when the form is submitted, it will be available in $_POST['checkboxName'], otherwise, isset($_POST['checkboxName']) will return false.
Basic script to test it
<?php
if (isset($_POST['heh']))
echo $_POST['heh'];
else
echo "Not checked";
?>
<form action='yourPage.php' method='post'>
<input type='checkbox' name='heh' />
<input type='submit' />
</form>
View it in action
http://robertsquared.com/so.php

i solve this problem on client side
i have a input of type hidden with the same name as the checkbox with the value of 0 and the checkbox right after the hidden field with the value of 1
if the checkbox is not checked i get the value of 0 from the hidden field and if someone checks i got the 1 from the checkbox.
so i only need to check if $value==1 then checked=checked

Related

Checked box should stay checked PHP

if i check the checkbox, the checkbox should stay checked. I got a form where it gets checked after submit, but it should staying checked without any Submit. is it possible with php?
Code:
$checkbox=false;
if (isset($_POST['psp-ele'])){
$checkbox=true;
};
?>
<input type="checkbox" name="psp-ele" id="Investnr" class="Investnr" <?php if ($checkbox==true) { echo "checked='checked'";}; ?> >
If you want the checkbox to stay checked when you load the page without a form submit then you should keep that information in the session and set the value from the session when parsing the checkbox:
In your form processor:
session_start();
$_SESSION['psp-ele'] = isset($_POST['psp-ele']);
Where ever you want to parse it:
<?php
// start the session if it has not already been started
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
?>
<input type="checkbox" name="psp-ele" id="Investnr" class="Investnr" <?php if ($_SESSION['psp-ele']) { echo 'checked'; }; ?> >
The initial load of your page that contains the form is likely to happen via a GET request - so simply add a check if the request method was GET, and also set your flag to true in that case:
$checkbox=false;
if ($_SERVER['REQUEST_METHOD'] == 'GET' || isset($_POST['psp-ele'])){
$checkbox=true;
};
If you want the form to be checked by default and after submit want to persist the users selection then you can simply add another condition which checks if the variable has been defined or not with isset.
if(!empty($_POST)){
if (isset($_POST['psp-ele'])){
$checkbox = true;
}else{
$checkbox = false;
}
}
<input type="checkbox" name="psp-ele" id="Investnr" class="Investnr" <?php if (!isset($checkbox) || $checkbox) { echo "checked='checked'";}; ?> >
The isset checks the checkbox when loading for the first time and the $checkbox variable does it after being submitted.

check if checkbox is not checked. BOTH status needed (checked and unchecked)

I've tried to get those checkbox that are unchecked. At this moment i'm just getting those that are checked. Here is my code. That value will be inserted on a table which i don't want to leave it null, that's why i need to get those checkbox unchecked, so that i could insert 1 for checked or 0 for unchecked:
<?php
if (!empty($_POST['menu'])) {
# code...
foreach ($_POST['menu'] as $value) {
# code...
echo "<p>ID Checkbox checked: ".$value;
}
}
?>
One of the reasons for what i need to get both status: checked or unchecked is because i don't want to leave database fields empty.
Unchecked checkboxes don't get POSTed. If you know what fields should be there, you'll probably have to list them out manually.
The wonderful thing about checkboxes is that when you don't have one checked, and you submit a form, nothing is sent to the server. Take this checkbox for example:
<input type="checkbox" name="test"/>
If you left it unchecked and looked for $_POST['test'] it would error out, as it is not set.
So, try doing this:
if(!isset($_POST['name_of_checkbox'])){
// Fill database with some empty value.
} else {
// Do what you need to do for checked value.
}
Hope that gives you some insight!
Say if they are named the same, and you know the number of checkbox you can use a for loop:
if (!empty($_POST['menu'])) {
for ($i=0; $i < 10; $i++) {
if(isset($_POST['menu'][$i])){
echo "Checkbox checked: " . $_POST['menu'][$i];
}else{
echo "Checbox uncheck #" . $i;
}
}
}
You can put the names in an array, then iterate:
$checkboxes = array('cbx1', 'cbx2', 'cbx3');
foreach ($checkboxes as $checkbox) {
if (isset($_POST[$checkbox])) {
echo "<p>ID Checkbox checked: " . $_POST[$checkbox];
} else {
echo "Checbox uncheck :" . $checkbox;
}
}
So yeah many ways to achieve this, it depends on the situation.
Check for #Artur approach as well for client side solution.
<input type="hidden" name="checkbox[8]" value="0">
<input type="checkbox" name="checkbox[8]" value="8">
This would be one way to also get 0's posted. Important part is that the name's are the same. So if checkbox is checked, it's value would override the hidden input value.
Thank you all for your time and be so kind to answer my question. The reason for what i needed to have those checkboxes unchecked and checked is because i have a dynamic menu and so i assign menus to users. Here is the solution i found with a friend of mine at work:
Code for the checkboxes. I query all the menus available on my table Menus so that i will show the administrator all the menus availables so then he could choose which menus he will assign to the users:
´
<table>
<tr>
<td>Menus a asignar:</td>
<td>
<?php
$query_menus_checkbox = mysql_query("SELECT id_menu, nombre_menu FROM menus");
while ($checkbox_mostrar = mysql_fetch_row($query_menus_checkbox)) {
# code...
?>
<input type="checkbox" name="menus[<?php echo $checkbox_mostrar[0]; ?>]" value="<?php echo $checkbox_mostrar[0] ?>"><?php echo $checkbox_mostrar[1] ?>
<p></p>
<?php
}
?>
</td>
</tr>
</table>
´
Then here is the code to process which checkboxes are checked or not to insert on my table (id_user is not shown but i have taken from another query which is not shown so you'll have to query yourself):
´
$res=mysql_query("select id_menu from menus");
$arid=array();
while($xd=mysql_fetch_assoc($res)){
$arid[]=$xd['id_menu'];
}
for($i=0;$i<count($arid);$i++){
$id_menu=$arid[$i];
$activo=(isset($_POST['menus'][$id_menu]) && $_POST['menus'][$id_menu]!="")?1:0;
$inserta_menus = mysql_query("INSERT INTO menus_usuarios(id_menu, id_usuario, estado) values ('$id_menu', '$id_user[0]', '$activo')");
}
´

If statement check if post is set

Hello I'm having some problem.
I want it to be checked by default, and if you unselect it and press submit I want it to be unchecked
<input type="checkbox" name="show_signature" value="1"<?php echo isset($_POST['show_signature'])) ? ' checked=""' : '' ?>>
This works good unchecking > submitting and checkbox is unchecked and same if you check it and send the form, it stays checked.
But, I want it to be checked by default. Should'nt this work?
if (isset($_POST['show_signature'])) {
echo ' checked=""';
} else {
echo '';
}
Tried this to
if (isset($_POST['show_signature']) || !isset($_POST['show_signature'])) {
echo ' checked=""';
} else {
echo '';
}
Okay; from the question, I got this process
When the page loads the first time, you want the checkbox to be checked.
When the page is submitted, if the checkbox is unchecked, let it remain unchecked; otherwise, let it be checked.
Try
/*making the assumption that the submission process starts when a submit button
with name **submit** is present, use this
*/
if (isset($_POST["submit"])){
value = '<input type="checkbox" name="show_signature"';
value .= (isset($_POST["show_signature"]))? 'checked="checked"': "";
value .= ' />';
print value;
}
else{ //when the page is initially loaded
print '<input type="checkbox" name="show_signature" checked="checked" />';
}
The reason the post depends on the submit button (or any other field)t is because if the user unchecks the box, the $_POST["show_signature"] variable will not be found, and the form will not be processed at all.
That should resolve the issue.
Hope the explanation is clear and this helps.

Getting Checkbox values when user edits form data. PHP

I have a form with checkboxes that users fill out and submit. I then have another form that allows them to edit the information they submitted. This second form pre-populates with the information they submitted on the first form. This is fine with text fields, but how do I pre-populate the checkboxes? I.e. if they checked a checkbox on the first form, how do I get the second form to recognise that and display a checked checkbox?
I'm new to Php so sorry I can't be more technical with this query!
Thanks
Luke
When you submit the form, you have the data on the next page. So if theres a checkbox looking like this:
<input type="checkbox" name="over18" value="1" />
You have to check if the person selected the "over 18"-field.
if ($_POST['over18'] == '1') {
$checked = 'checked="checked"';
}
else {
$checked = ''; //If it's not checked
}
Then your output for the checkbox looks like this:
echo '<input type="checkbox" name="over18" value="1" ' . $is_checked .'/>';
So everytime the Checkbox is checked, the next page checks the Checkbox too.

using radio buttones as check box

I am learning how to develop WordPress plugins from this tutorial series and now I am on this tutorial , but I found a strange thing: there is used two RadioButtones to get values "True" or "False" where they could use one CheckBox
<label for="devloungeHeader_yes">
<input type="radio" id="devloungeHeader_yes" name="devloungeHeader" value="true" <?php if ($devOptions['show_header'] == "true") { _e('checked="checked"', "DevloungePluginSeries"); }?> />
Yes
</label>
<label for="devloungeHeader_no">
<input type="radio" id="devloungeHeader_no" name="devloungeHeader" value="false" <?php if ($devOptions['show_header'] == "false") { _e('checked="checked"', "DevloungePluginSeries"); }?>/>
No
</label>
I saw something similar on joomla admin page, where there was used 2 radio buttons to get the same result.
So, is there any (html, css, javascript, php, just any) advantage of using two radio buttons instead of one checkbox?
Actually I found out why using two radio buttons with same names and different values "True" and "False" is better than checkboxes. when a checkbox is NOT checked, it will not be submitted to the server. But when you use radio buttons with "True" and "False" values those radio buttons will be submitted on the server, so php will get result from html form anyway. So with ckeckbox you have only two options:
1) when chebox is checked and is submited (value == "checked")
2) when checkbox is Not checked and it is not submited
with php you have those two options:
<?php
if (isset($_POST['testCheckBox'])) {
// it is submited so it means it is Checked!
} else {
// it is not submited because it is not checked or there is something wrong!
}
?>
But with radio buttons you have three options:
1) when radio "True" is checked and is submited
2) when radio "False" is checked and is submited
3) when radio is not SUBMITED, so something is not working properly
php example:
<?php
if (isset($_POST['testRadioButton'])) { // testRadioButton is submited!
if($_POST['testRadioButton'] == "true"){
// True is checked, do something
} elseif(($_POST['testRadioButton'] == "false"){
// False is checked, do something
}
} else {
// it not Submited! so there is definitely something wrong with code
}
?>

Categories