I am making a form and one of the inputs are a number of checkboxes that come from a database. If the form isn't filled out correctly, the user should be returned to the form but with the selected checkboxes should still be checked once a user returns.
The page containing the form uses an if, if the user made a mistake, he/she receives a form that contains sessions so the stuff that was filled in is still there. The other form doesn't have sessions.
This is the code I use to read out the checkbox options from the database:
$STH = $DBH -> prepare("SELECT * FROM tbloptions");
$STH -> execute();
$STH -> setFetchMode(PDO::FETCH_OBJ);
while($row = $STH -> fetch())
{
$optionID = $row -> optionID;
$option = $row -> option;
?>
<input type="checkbox" name="<?php echo $option ?>" value="<?php echo $optionid ?>"> <?php echo $option ?><br>
<?php
}
?>
what code should I use for the form with the sessions and what code should I use to create the sessions
thanks
Adding square braces to the checkbox name creates an array of the selected values in the group
<input type="checkbox" name="chk_group[]" value="<?php echo $optionid ?>" /><?php echo $option ?><br />
This can be retrieved in PHP with a simple loop:
<?php
if (isset($_POST['chk_group'])) {
$optionArray = $_POST['chk_group'];
for ($i=0; $i<count($optionArray); $i++) {
echo $optionArray[$i]."<br />";
}
}
?>
Next, you can redisplay the form with the "checked" arg if the option is in the $optionArray array
This depends how you process your form variables. The following assumes no processing and that the data is POSTed.
Determine if the value of checkbox "name" is set to "value" and if so, check it:
<input type="checkbox" name="<?php echo $option ?>" value="<?php echo $optionid ?>" <?php if($_POST[$option]==$optionid){echo' checked="checked"';} ?>> <?php echo $option ?>
...
Related
I have a program where I am populating the check box, once I click on the submit button, I am inserting the data into DB and I want to retain the checkbox state as checked for the values that I have inserted, so that when a user logs in again he can see the items he has checked the previous time. This is my code
<?php
$accQry = "select * from brands";
$result1 = mysql_query($accQry, $db1->conn);
$i = 1;
while ($row = mysql_fetch_assoc($result1)) {
?>
<label> <input type="checkbox" value="<?php echo $row['brand_id']; ?>" name="chk1[]" ><?php echo $row['brand_name']; ?></label>
<?php $i++;
}
?>
This is the code to populate and I don't know how to go about it further.
Checkbox has attribute checked, which should be set when you want to check it - how checkbox works
I have an html form (and accompanying php code) that allows user to input task names, which are stored in a PHP array $task_list[].
I also have, below the task list, a dropdown from which users can select a desired value. I want to create a button modify which will allow users to change the value they have selected.
For instance, if the task list is:
Get up
Take a bath
Go for a jog
Go to school
Come back home
A user should be able to select "Go to school", and having done so, click Modify and change that to "Go to work", or something else.
I've made the select dropdown list work and can access the selected value and store it in a variable $selected. But I am completely flummoxed as to how I can allow users to change the value in the $task_list array.
My code–
task_list.php:
<form action="." method="post" >
<!//select dropdown>
<select name='taskid'>
<?php foreach( $task_list as $id => $task ) : ?>
<option value="<?php echo $id; ?>">
<?php echo $task; ?>
</option>
<?php endforeach; ?>
</select>
<?php foreach( $task_list as $task ) : ?>
<input type="hidden" name="tasklist[]" value="<?php echo $task; ?>">
<?php endforeach; ?>
<br />
<label> </label>
<input type="hidden" name="action" value='modify'>
<input type=submit value="Modify Task">
<br />
<label> </label>
<input type="hidden" name="action" value='promote'>
<input type=submit value="Promote Task">
</form>
index.php:
//get selected value
function getSelected()
{
if(isset($_POST['taskid']))
{
$myvalue = $_POST['taskid'];
}
else
{
$myvalue = $task_list[0];
}
return $myvalue;
}
//skipping ahead to modify field (all other buttons work perfectly):
case 'modify':
$myval = getSelected(); //$myval returns index of selected item
$selected = $task_list[$myval]; //selected item
break;
I just want to allow the user to click modify and change the value they selected in the $task_list array.
Thank you.
I am currently displaying a table with checkbox and the checkbox is displayed using while loop. For the value of each checkbox, I used value = "$key" . The problem that I am currently having now is, how can I post the value of the checkbox to another php page ?`
<?php $sm_sql = "SELECT * FROM submodule WHERE mod_id = '1'";
$sm_res = DB_Query($sm_sql);
while($sm_row = DB_FetchRow($sm_res)) {?>
<tr> <?php
?> <td><div align="center"> <?php echo $sm_row["submod_name"];
?></div>
</td>
<!-- key 1 = submod_create_id -->
<td> <div align="center">
<?php
$fi_sql = mysql_query("SELECT * FROM finance_controlling WHERE staff_id = '".$STAFF_ID."'");
<?php
$fi_sql = mysql_query("SELECT * FROM finance_controlling WHERE staff_id = '".$STAFF_ID."'");
while($row = mysql_fetch_assoc($fi_sql))
{
foreach($row as $key => $value)
{
if($key == $sm_row["submod_create_id"])
{
if($value == '1')
{ ?><input type=checkbox checked="checked" name="$key" id="$key"> <?php
print $key; //it prints out the correct key
} else { ?><input type=checkbox name="$key" id="$key"> <?php
print $key;
}
}
}
}
?>
Above are my checkbox in Module_Form.php.
Below are Summary.php page where the value of the checkbox should be displayed on.
if ($_POST["Submit"] == "Review Risk")
{
$a = $_POST['fi_pp_c']; echo $a;
}?>
The problem now is that the checkbox value are not passed to another page. Ive tried json_encode but there are still no value displayed.
There are a few thing I feel should be addressed here.
First up: Prepared statements
Having raw SQL in your PHP code which just inserts variables inside some quotes is dangerous. It might be ok for your current use case, but in future if this changes, it is all too easy for a developer to just make $STAFF_ID a $_POST['varName'], which immediately introduces SQL injection.
Please take some time to read up on prepared statements and stored procedures in SQL/PHP: http://php.net/manual/en/pdo.prepared-statements.php
Second up: HTML attribute values
This is ok and it is valid HTML, however, I'd suggest it is good practice to include all attribute values in quotes, so that if there are spaces in values, they are correctly interpreted. This is clearly not going to happen with the type attribute but it does make code easier to read and to process using more primitative parsers, if it were:
<input type="checkbox" checked="checked" name="<?= $key ?>" id="<?= $key ?>">
As to the original question: have you enabled debugging? Primatively you can do this by adding error_reporting(E_ALL); to the top of your PHP file.
The issue I suspect you are facing is that is the checkbox is not checked, then there is no value for the key with the same name passed in the HTTP POST request.
For example, if you have:
<input type="checkbox" name="myCheckbox" />
And that checkbox is unchecked when the form is submitted, then in PHP $_POST['myCheckbox'] is null.
So the solution is to check whether these fields are null, e.g.:
if(isset($_POST['myCheckbox'])) {
$a = $_POST['myCheckbox'];
echo $a;
}
I generally think this is a gap in protocol, and that unchecked checkboxes should be submitted in forms with a value of 0, but ho hum!
In your code :
?><input type=checkbox checked="checked" name="$key" id="$key"> <?php
you closed your PHP tag and reopened it after the HTML.
You need to reopen it to print your $key in the name and id parameters. As it is, it`s only treated as text. The browser just thinks that the id and name attributes are "$key".
?><input type=checkbox checked="checked" name="<?= $key ?>" id="<?= $key ?>"> <?php
and here :
} else { ?><input type=checkbox name="<?=$key ?>" id="<?= $key ?>"> <?php
This would solve your current problem, as long as the "name" of the checkbox is "fi_pp_c" otherwise, it will be stored in whatever is named the checkbox.
You can just var_dump($_POST); to check where you data is stored if you still have issues.
I am currently doing up a list of names that has signed up for a activity which is then needed to go through another selection process and to be put into the database. I have currently done the getting and displaying of names from the people that has signed up.
However, I am not too sure on the process of how I can get those checked which is being selected in the selection process.
This is currently the codes that I have done to get and display the names of the people who have signed up. Upon clicking submit, it would go to another page which would then process, get those checked and marked as 1 or true to the database (MySQL) or either set as 0 or false if it has not been checked.
<?php
if ($totalShortlist > 0) {
?>
<?php
while ($row = mysqli_fetch_assoc($result)) {
$firstName = $row['first_name'];
$lastName = $row['last_name'];
?>
<form id="selectionProcess" action = "doShortlistProcess.php?id=<?php echo $id ?>" method = "post">
<fieldset data-role="controlgroup">
<label><input type="checkbox" name="selectionProcess" id="selectionProcess" value="<?php echo $id ?>"/><?php echo $firstName; ?> <?php echo $lastName; ?></label>
</fieldset>
<?php
}
?>
<input type="submit" class="btnSelect" data-theme="b" data-inline="true" name="shortlistCandidate" value="Submit Shortlisted Candidates"/>
</form>
<?php
}
// end for loop
else {
echo "No candidates to be shortlisted";
}
mysqli_close($link);
?>
The $id as shown is the brought over from the list of categories on the previous page, which allows to get all the names in that categories to be displayed.
Your code places the form in the wrong place compared to the while loop. The action also doesn't need you to compose a query string. Better code (careful, I've also cut out some presentation):
if ($totalShortlist > 0) {
?>
<form id="selectionProcess" action = "doShortlistProcess.php" method = "post">
<fieldset>
<?php
// use while loop to display a tick box for each item
while ($row = mysqli_fetch_assoc($result)) {
$firstName = $row['first_name'];
$lastName = $row['last_name'];
?>
<label>
<input type="checkbox" name="selectionProcess" id="selectionProcess" value="<?php echo $id ?>"/>
<?php echo $firstName; ?> <?php echo $lastName; ?>
</label>
<?php
} // end of while loop
?>
</fieldset>
<input type="submit"/>
</form>
<?php
} // end of shortlist > 0
I recommend you test this code using the GET method. It will show you what form the submission takes.
To process the result, you should use the list of responses, process it and turn it into one or more SQL statements.
An alternative would be to use an action for each checkbox, but then use ajax to a php page that would modify the status of single subscriber. The change would be made immediately as users click.
still no solution on this question
So this is what I'm trying to do:
Have a product in a shopping cart with options. the options will be selectable through <input type="checkbox/> And the products are stored based on id's in sessions with php.
Right now I have the candies submitting as an array (like below) But I'm not sure how to add it to that specific product within the session.
My Input for the options is like this:
<?php foreach($options as $option): ?>
<input type="checkbox" name="candies[]" value="<?php echo $option['candy_name']; ?>" /><?php echo $option['candy_name']; ?><br/>
<?php endforeach; ?>
My current code for adding the product to the session is like this:
...
case "add":
$_SESSION['cart'][$product_id]++;
header('location: ../../cart.html');
break;
...
I've also placed $candies = $_GET["candies"]; above the above code to get the options.
How can I make it so the options array is stored in the session for each individual product?
In this image below, you can see what I'm talking about... I am wanting to display each selected option under the options column for the specific product.
this might not be the exact code you are looking for but this should serve as your guide to what you want to achieve.
Let's say you want to get the product options values from you database's productOptions.
$resultSet = mysql_query("SELECT * FROM productOptions");
Now we display the checkboxes to your form based on the result of the query.
while($row = mysql_fetch_assoc($resultSet)){
echo "<input type='checkbox' name='options[]' value='{$row['optionsID']}' />";
}
After displaying the check boxes to our form, we get the checked value from those check boxes that where selected.
if(isset($_POST['yourSubmitButtonName'])){
$productSelected = array();
if(!empty($_POST['options'])){
foreach($_POST['options'] as $options){
$optionsSelected[] = $options;
}
}
}
Now, set the array of options the the $_SESSION variable.
$_SESSION['yourProductID'] = $optionsSelected;
Then we display the options for a product this way
foreach($_SESSION['yourProductID'] as $productOptions){
echo $productOptions;
}
It looks like you've got the correct HTML structure but your code is disjointed. The simplest answer is to do something like this
$_SESSION['cart'][$product_id] = array('options' => $_POST['candies']);
Then you would do something like
foreach($_SESSION['cart'][$product_id]['options'] as $opt) {
echo $opt;
}
Code should look like this first html take checkbox
<form action="sample.php" method="post">
<input type="checkbox" name="candies[]" value="Candy1" />
<input type="checkbox" name="candies[]" value="Candy2" />
<input type="checkbox" name="candies[]" value="Candy3" />
<input type="submit" value="Submit" />
<form>
then session
<?php
session_start();
$result = array();
foreach ( $_POST['candies'] as $key=>$row ) :
$result[$key] = $row[$key];
endforeach;
$_SESSION['candies'] = $result;
print_r($_SESSION['candies']);
?>