How to remember checkbox input in PHP Forms - php

For usability purposes I like to set up my form fields this way:
<?php
$username = $_POST['username'];
$message = $_POST['message'];
?>
<input type="text" name="username" value="<?php echo $username; ?>" />
<textarea name="message"><?php echo $message; ?></textarea>
This way if the user fails validation, the form input he entered previously will still be there and there would be no need to start from scratch.
My problem is I can't seem to keep check boxes selected with the option that the user had chosen before (when the page refreshes after validation fails). How to do this?

My first suggestion would be to use some client-side validation first. Maybe an AJAX call that performs the validation checks before continuing.
If that is not an option, then try this:
<input type="checkbox" name="subscribe" <?php echo (isset($_POST['subscribe'])?'checked="checked"':'') ?> />
So if subscribe is = 1, then it should select the box for you.

For Example, consider the following code for checkbox :-
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("PHP", $_POST["course"]))) {
echo "checked";
} ?> value="PHP" />
Then, this would remember the checkbox of "PHP" if it is checked, even if the validation for the page fails and so on for "n" number of checkboxes as shown below:-
<label for="course">Course:</label>
PHP<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("PHP", $_POST["course"]))) {
echo "checked";
} ?> value="PHP" />
HTML<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("HTML", $_POST["course"]))) {
echo "checked";
} ?> value="HTML" />
CSS<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("CSS", $_POST["course"]))) {
echo "checked";
} ?> value="CSS" />
Javascript<input type="checkbox" name="course[]" id="course" <?php if ((!empty($_POST["course"]) && in_array("Javascript", $_POST["course"]))) {
echo "checked";
} ?> value="Javascript" />
And most importantly, do not forget to declare the "course" variable as an array at the start of the code as shown below :-
$course = array();

I have been battling how to create sticky check box (that is able to remember checked items any time you visit the page). Originally, I get my values from a database table. This means that my check box value is entered to a column on my db table.
I created the following code and it works just fine. I did not want to go through that whole css and deep coding, so...
CODE IN PHP
$arrival = ""; //focus here.. down
if($row['new_arrival']==1) /*new_arrival is the name of a column on my table that keeps the value of check box*/
{$arrival="checked";}// $arrival is a variable
else
{$arrival="";};
echo $arrival;
<b><label for ="checkbox">New Arrival</label></b>
<input type="checkbox" name ="$new_arrival" value="on" '.$arrival.' /> (Tick box if product is new) <BR><BR>

<input type="checkbox" name="somevar" value="1" <?php echo $somevar ? 'checked="checked"' : ''; ?>/>
Also, please consider sanitising your inputs, so instead of:
$somevar = $_POST['somevar'];
...it is better to use:
$somevar = htmlspecialchars($_POST['somevar']);

When the browser submits a form with a checked checkbox, it sends a variable with the name from the name attribute and a value from the value attribute. If the checkbox is not checked, the browser submits nothing for the checkbox. On the server side, you can handle this situation with array_key_exists(). For example:
<?php
$checkedText = array_key_exists('myCheckbox', $_POST) ? ' checked="checked"' : '';
?>
<input type="checkbox" name="myCheckbox" value="1"<?php echo $checkedText; ?> />
Using array_key_exist() avoids a potential array index undefined warning that would be issued if one tried to access $_POST['myCheckbox'] and it didn't exist.

You may add this to your form:
<input type="checkbox" name="mycheckbox" <?php echo isset($_POST['mycheckbox']) ? "checked='checked'" : "" ?> />
isset checks if a variable is set and is not null. So in this code, checked will be added to your checkbox only if the corresponding $_POST variable has a value..

My array has name="radioselection" and value="1", value="2", and value="3" respectively and is a radio button array... how to I check if the radio value is selected using this code
I tried:
<?php echo (isset($_POST['radioselection']) == '1'?'checked="checked"':'') ?> />

Related

Getting check box values as checked from database codeigniter

I'm trying to get check box values inserted into my database as checked.. I'd inserted it using the implode method as string. It inserted the values successfully., but my condition to get the check box value "checked" is not working..
<label>Some text</label>
<input type="checkbox" name="text[]" value="text1"
<?php echo set_checkbox('text', $row->Some_text)== 'text1' ? "checked" : "";?>>text1
<input type="checkbox" name="text[]" value="text2"
<?php echo set_checkbox('text', $row->Some_text)== 'text2' ? "checked" : "";?>>text2
<input type="checkbox" name="text[]" value="text3"
<?php echo set_checkbox('text', $row->Some_text)== 'text3' ? "checked" : "";?>>text3
<input type="checkbox" name="text[]" value="text4"
<?php echo set_checkbox('text', $row->Some_text)== 'text4' ? "checked" : "";?>>text4
I wrote model for edit as :
public function edit($id)
{
$sometext = $this->input->post('text');
$data=array(
'Some_text'=>json_encode(implode(",", $sometext)),
);
$this->db->set($data);
$this->db->where('User_id',$id);
$this->db->update('tbl_check');
$query = $this->db->get('tbl_check');
return $query->row();
}
And edit is working well..
Sometimes the use of functions from frameworks just make it totally unnecessarily and dirtier.
<input type="checkbox" name="text[]" value="text1" <?php echo ($yourVar == 'text1' ? 'checked' : null); ?>>
Just get the data from the Model. and pass it to the check box page.
$data['check_box_data']=$query->row_array();
$this->load->view('page',$data);
View:
<?php
$c_box1=$c_box2=$c_box3='';
$chk_data=explode(',',$chk_box_data); // $chk_box_data is which is from DB
foreach($chk_data as $list)
{
//chk_box1_value1,2,3 are original check box values
if($list=='chk_box1_value'){$c_box1='checked';}
if($list=='chk_box2_value'){$c_box2='checked';}
if($list=='chk_box3_value'){$c_box3='checked';}
}
?>
label>Some text</label>
<input type="checkbox" name="text[]" value="text1"
<?php echo $c_box1;?>>text1
<input type="checkbox" name="text[]" value="text2"
<?php echo $c_box2;?>>text2
<input type="checkbox" name="text[]" value="text3"
<?php echo $c_box3;?>>text3
Try this....
Using standard CodeIgniter functions:
form_checkbox('fieldname', '1', set_checkbox('fieldname', '1', (TEST YOUR DB DATA HERE)));
Example:
form_checkbox('fieldname', '1', set_checkbox('fieldname', '1', (!empty($data_from_db))));
Explanation:
set_checkbox() determines whether to output checked="checked" and thus show your field as checkmarked or not.
The third parameter of set_checkbox() determines whether the initial state of your checkbox will checked/not-checked. If the third parameter evaluates to TRUE the first time the form is loaded, the checkbox will be ticked; if it evaluates to FALSE, it won't be marked.
So, when editing data from a table, use the Controller to get the data from the table and pass it to the form. In your form, test the data from your table in the third parameter of set_checkbox().
In my example above, the data for FIELDNAME was stored in the table as "1" or "0".
When the edit form is loaded, the third parameter of SET_CHECKBOX tests, "Is the data from the table empty?" If there is data, !empty() returns TRUE, causing set_checkbox() to set the DEFAULT STATE to CHECKED.
The key is using the THIRD PARAMETER of set_checkbox() to evaluate your existing value.
You are using set_checkbox incorrectly. Look at the documentation: do not use this in a conditional statement. Your question doesn't give much information, but I assume you want something like this:
<input type="checkbox" name="text[]" value="text1"
<?php echo set_checkbox('text[]', 'text1');?>>text1
<input type="checkbox" name="text[]" value="text2"
<?php echo set_checkbox('text', 'text2');?>>text2
<input type="checkbox" name="text[]" value="text3"
<?php echo set_checkbox('text', 'text3');?>>text3
<input type="checkbox" name="text[]" value="text4"
<?php echo set_checkbox('text', 'text4');?>>text4

Select Value from DB Array inside check box input

Hello I am using various check boxes with different values and than storing the vales inside DataBase as all the checkboxes values are store inside Array
<input type="checkbox" value="Gym" id="details_10" name="utilities[]">
<input type="checkbox" value="Spa" id="details_11" name="utilities[]">
and than store in the database like: Gym, Spa.
Later I am making MySQL query inside edit form where I will be able to edit those and other parameters. For the other inputs I am using:
<?php if($row['data'] == 'Sample Data'){echo 'selected="selected"';}?>
In this case I would like to use something like the following:
<input type="checkbox" value="Gym" id="details_10" name="utilities[]"<?php if($row['utilities'] == 'Gym'){echo 'checked"';}?>>
Any help to achieve this result will be very welcome.
I've always used this in these cases.
<?php
if($row['utilities'] == 'Gym')
{
?>
<input type="checkbox" value="Gym" id="details_10" name="utilities[]" checked="checked">
<?php
}
else
{
?>
<input type="checkbox" value="Gym" id="details_10" name="utilities[]">
<?php
}
?>

Storing checkbox values in sessions and then re-selecting check boxes checked when they came back to add some more

I am trying to pass my checkbox values through a session variable if the user goes back by clicking add more books link. I want to show them previously selected check boxes are checked. I tried in chklist.php page
if(isset($_SESSION['pro'])){
echo $_SESSION['pro'];}
shows values like 1_2_5 which are present in session array.
Here is my html code of checkboxes. I have about 24 checkboxes with the same name as product[].
<name="product[]" type="checkbox" value="1" alt="1607.00" />
<name="product[]" type="checkbox" value="2" alt="1607.00" />
and so on
Here I am setting my session after POST of checkboxes .
$_SESSION['pro'] = implode('_', $_POST['product']);
in nextpage chkout.php.
How to make previously selected checkboxes are checked when user came back to firstpage(chklist.php) by clicking ADD MORE BOOKS link present in chkout.php, can any body write the code what i need add to my html.
You can put products array into session then access it as an array.
When setting:
$_SESSION["products"] = $_POST["product"];
When listing products, you should check the values from session:
for($i = 0; $i < 24; $i++) {
echo '<name="product[]" type="checkbox" value="'.$i.'" alt="1607.00"';
if(in_array($i, $_SESSION["products"])) echo ' checked="checked" ';
echo ' />';
}
This is the basic idea and example code.
--UPDATE--
According to your comments:
Inside the form, we will print products as follow:
<?php
session_start();
$session_products = array();
if(array_key_exists("products", $_SESSION))
{
if($_SESSION["products"] != null)
{
$session_products = $_SESSION["products"];
}
}
<form method="post" action="newtest.php">
<input name="product[]" type="checkbox" value="1" <?php if(in_array("1", $session_products)) echo "checked='checked'"; ?> alt="1607.00" />
<input name="product[]" type="checkbox" value="2" <?php if(in_array("2", $session_products)) echo "checked='checked'"; ?> alt="1848.00" />
<input name="product[]" type="checkbox" value="3" <?php if(in_array("3", $session_products])) echo "checked='checked'"; ?> alt="180.00" />
<input name="product[]" type="checkbox" value="4" <?php if(in_array("4", $session_products)) echo "checked='checked'"; ?> alt="650.00" />
and so on upto 24 ...
</form>
Inside the code where the form values are posted, we will put these values into session:
<?php
include("config.php");
session_start();
if(isset($_POST))
{
$_SESSION["products"] = $_POST["product"];
}
?>

Pass a php variable into another php file

i have a php file which stores a variable, and i need to create a submit form which passes this variable.
So the code of the current file is:
if(isset($_POST['Submit'])) {
echo "<pre>";
$checked = implode(',', $_POST['checkbox']);
echo $checked;
}
I have to insert the submit form and on click it goes to another php file, i need to get there the $checked variable.. how can i store this variable?..
Thanks you!
The principle of POSTing is that you can send all the data to the next .php page.
<?php
if ($checked == 1) {
$checked = 'checked="checked"';
}
else {
$checked = '';
}
?>
<form action="POST" method="target_file.php">
<input type="hidden" name="variableA" value="Something I want target_file.php to know" />
<input type="hidden" name="variableB" value="Something else I want target_file.php to know" />
<input type="checkbox" name="gender" value="male" <?php echo $checked ?>" />
</form>
Your target_file.php:
echo "Here I am :), variableA: ".$_POST['variableA'];
echo "Here I am :), variableB: ".$_POST['variableB'];
echo "Here I am :), My gender is: ".$_POST['gender'];
Also, don't trust on checking your field values that are send through the $_POST. Check what every value is and if it meets certain criteria before sub-statements may be executed.

PHP check boxes and URL rewriting

Hope someone can help me with my code. i am using rewritten URL's and have this piece of code on a form. When the page first loads mypage.htm, the type_24 checkbox get's checked by default. If they check the type_12 box, i want the type_24 box to uncheck.
My problem is, if i check the type_12 box, the page refreshes and both the type_12 and type_24 boxes are checked.. which is not what i want. I think it's because i'm reloading my rewritten URL in my action because it works fine if i just have php file as the action.
Any ideas how i can fix my code so that it only has the type_12 checked when i check the type_24 box?
<form name="frmrefresh" id="frmrefresh" method="post" action="mypage.htm">
<input type="checkbox" name="type_12" id="type_12" <?php if(isset($_POST['type_12']) && $_POST['type_12']=="12"){?> checked="checked"<?php }?> value="12" onClick="uncheck24(this);" /> <label>12</label>
<input type="checkbox" name="type_24" id="type_24" <?php if(isset($_GET['id']) && $_GET['id']!=''){?>checked="checked"<?php }?><?php if(isset($_POST['month_24']) && $_POST['type_24']=="24"){?> checked="checked"<?php }?> value="24" onClick="uncheck12(this);"/> <label>24 Months</label>
<input type="hidden" name="id" value="<?php echo $_REQUEST['id'];?>" />
</form>
In the header i have the functions:
function uncheck12(obj)
{
if (obj.checked == true)
{
document.getElementById("type_12").checked = false;
document.frmrefresh.submit();
}
}
function uncheck24(obj)
{
if (obj.checked == true)
{
document.getElementById("type_24").checked = false;
document.frmrefresh.submit();
}
}
A number of remarks:
Consider using radio buttons instead of checkboxes
I think you mean isset($_POST['type_24']) instead of isset($_POST['month_24'])
As to your problem, I bet your rewrite rule is something like:
RewriteRule ^mypage.htm$ mypage.php?id=5
This means that when the form gets submitted via POST, PHP will still set the $_GET['id'] variable for you since it's in the query string. And since you check the '24' option whenever $_GET['id'] is set, the second checkbox will always get checked.
To fix this you could consider adding the check $_SERVER['REQUEST_METHOD'] == 'GET':
<form name="frmrefresh" id="frmrefresh" method="post" action="mypage.htm">
<input type="checkbox" name="type_12" id="type_12" <?php if(isset($_POST['type_12']) && $_POST['type_12']=="12"){?> checked="checked"<?php }?> value="12" onClick="uncheck24(this);" /> <label>12</label>
<input type="checkbox" name="type_24" id="type_24" <?php if(isset($_GET['id']) && $_GET['id']!='' && $_SERVER['REQUEST_METHOD']=='GET'){?>checked="checked"<?php }?><?php if(isset($_POST['type_24']) && $_POST['type_24']=="24"){?> checked="checked"<?php }?> value="24" onClick="uncheck12(this);"/> <label>24 Months</label>
<input type="hidden" name="id" value="<?php echo $_REQUEST['id'];?>" />
</form>

Categories