Get checked or not checked multi value checkbox - php

Hi everyone I have a form with 5 checkboxes, once I run the post I would like to have all the checkboxes with the current status.
Example:
checkbox 1: on
checkbox 2: off
checbox 3: on
checkbox 4: off
checkbox 5: off
This is my code but it doesn't work with non-on states
<?php
if(isset($_POST['submit'])){
$array = $_POST["check_list"];
}
?>
<form action="" method="post">
<input type="checkbox" name="check_list[]"><label>Mon</label>
<input type="checkbox" name="check_list[]"><label>Tue</label>
<input type="checkbox" name="check_list[]"><label>Wed</label>
<input type="checkbox" name="check_list[]"><label>Thu</label>
<input type="checkbox" name="check_list[]"><label>Fri</label>
<input type="submit" name="submit" Value="Submit"/>
</form>
How can I get all the checkboxes with the statuses sent in the post?
Thank You

The value keyword can be used to specify the value:
Hardcoded Values
$days = ['mon', 'tue', 'wed', 'thu', 'fri'];
if(isset($_POST['submit'])){
$array = $_POST["check_list"];
foreach ($days as $day){
$isChecked = in_array($day, $array);
echo $day . ' is ' . ($isChecked ? ' checked' : ' not checked') . '<br />';
}
}
?>
<form action="" method="post">
<?php
foreach ($days as $day){
echo '<input type="checkbox" name="check_list[]" value="' .$day.'"><label>'.$day.'</label>';
}
?>
<input type="submit" name="submit" Value="Submit"/>
</form>
Dynamic Values
If the fields get added dynamically, hidden inputs can be used. The following snippet adds a hidden input for every available option. These hidden inputs can then be used to determine if there is an associated checkbox, and thus get the value.
Checkout the following example:
<?php
if(isset($_POST['submit'])){
$options = $_POST["check_list_options"];
$checkedValues = $_POST["check_list_values"];
foreach ($options as $optionId){
$isChecked = array_key_exists($optionId, $checkedValues);
if($isChecked){
echo 'option ' . $optionId . ' is checked and has value: '.$checkedValues[$optionId].'<br />';
}else{
echo 'option ' . $optionId . ' is not checked<br />';
}
}
}
?>
<form action="" id="checklist_form" method="post">
<div class="results">
</div>
<button type="button" id="add_days">
Add days
</button>
<input type="submit" name="submit" Value="Submit"/>
</form>
<script>
var addDays = document.querySelector('#add_days');
var form = document.querySelector('#checklist_form');
var results = document.querySelector('.results');
addDays.addEventListener('click', function(){
var inputId = document.querySelectorAll('.input').length;
results.innerHTML += '<input type="hidden" name="check_list_options[]" value="'+inputId+'" />' +
'<input type="checkbox" name="check_list_values['+inputId+']" value="mon'+inputId+'" class="input" />' +
'<label>Day '+inputId+'</label>' +
'<br />';
})
</script>

You can do this by giving a name to each checkbox or by adding the key to the name of checkbox, and create an array that contains the name of each checkbox, then check in a loop if the equivalent checkbox is set:
$checkboxes = ['checkbox 1', 'checkbox 2', 'checkbox 3', 'checkbox 4', 'checkbox 5'];
if(isset($_POST['submit'])){
foreach($checkboxes as $key=>$value) {
echo $value.': ';
if(isset($_POST["check_list"][$key])) echo 'on '; else echo 'off ';
}
}
?>
<form action="" method="post">
<input type="checkbox" name="check_list[0]"><label>Mon</label>
<input type="checkbox" name="check_list[1]"><label>Tue</label>
<input type="checkbox" name="check_list[2]"><label>Wed</label>
<input type="checkbox" name="check_list[3]"><label>Thu</label>
<input type="checkbox" name="check_list[4]"><label>Fri</label>
<input type="submit" name="submit" Value="Submit"/>
</form>

Related

I want to calculate total price of subjects given and store it in database

I have no idea how to calculate total price of this subjects using php.
help me with it.
<div id="mydiv" style="display:none">
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
<div id="mydiv1" style="display:none">
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="science">science<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
I want to calculate price total of this checkboxes and store it in database with its names using php
php part
if(isset($_POST['subject']))
{
$classes=$_POST['subject'];
$prices = array(
'biology' => 60,
'physics' => 200
);
$sum = array();
$getkeys = array_keys($_POST);
foreach($prices as $key => $value)
{
if(in_array($key, $getkeys)) $sum[] = $value;
}
$ar=array_sum($sum);
echo $ar;
if($classes)
{
$subject = implode(',', $ar);
$query="INSERT INTO feedetails (subjects,price) VALUES ('".$subject."','".$price."')";
if(mysqli_query($conn,$query))
{
echo ("<SCRIPT LANGUAGE='Javascript'>
window.alert('Your fee has been updated.Please proceed to pay.');
window.location.href='payment.php';
</SCRIPT>");
}
}
It appears that your summing strategy was not working, there were numerous issues there including this:
$getkeys = array_keys($_POST);
which appears as an attempt to get the subjects submitted, however they are in their own sub-array of $_POST, i.e. $_POST['subject']
This gets you the summing of the price information you require, however you will need to test your database INSERT code and debug this to ensure you are storing the data required correctly.
if (!empty($_POST['subject'])) {
$prices = [
'biology' => 60,
'physics' => 200,
'maths' => 300,
'science' => 400,
];
$sum = 0;
foreach ($_POST['subject'] as $subject) {
if (!empty($prices[$subject])) {
$sum += $prices[$subject];
}
}
echo '<pre>';
echo '$sum ' . print_r($sum, true);
echo '</pre>';
exit;
// process database inserts here
}
Additionally, when testing your code I notice you had hidden the checkboxes, to resolve this, use the following:
<div id="mydiv">
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="science">science<br>
<input type="submit" value="Calculate" name="submit" class="wpcf7-submit">
</div>
Try This may be help:
I am not doing all code just you asked for sum part.
Rest you can do Ask if any confusion.
HTML
<form method='post'>
<div id="mydiv" >
<input type="checkbox" name="subject[]" value="biology">biology<br>
<input type="checkbox" name="subject[]" value="physics">physics<br>
<input type="checkbox" name="subject[]" value="maths">maths<br>
<input type="checkbox" name="subject[]" value="social">social<br>
<input type="checkbox" name="subject[]" value="ssc">ssc<br>
<input type="submit" value="Calculate" name="submit"
class="wpcf7-
submit">
</div>
PHP
<?php
$classes =$_POST['subject'];
$prices = array('biology' => 60,'physics' =>
200,'maths'=>100,'ssc'=>40,'social'=>150);
$sum = 0;
echo 'Subject::Price<hr/>';
foreach($classes as $key=>$sub){
if(array_key_exists($sub,$prices)){
echo $sub.'::'.$prices[$sub]."<br />";
$sum = $sum+$prices[$sub];
}
}
echo '<hr/>';
echo $sum;
?>
OUTPUT

Codeginiter retriveing values of checked checkbox

Im developing form application. Inside the form there are textboxes,textarea, checkboxes checkboxes are populated according to array. and i pass all the form values to controller . Values of textboxes, texarea print correctly. Problem is there only prints last value of checked checkbox. how do i print all checked box values. please help me & please find the code i used.
askQuestion.php (view)
<?php echo form_open('homepage/test'); ?>
<p>
<div>
<div class="form-group">
Question Title:<br/>
<input type="text" value="" name="">
</p>
<div>
<div class="form-group">
<p>
Description: <br/>
<textarea name="decription" rows="5" cols="100"> </textarea>
</p>
<?php
$chk_group =array('1' => 'red',
'2' => 'aa',
'3' => 'bb',
'4' => 'cc',
'5' => 'dd'
);
var_dump($chk_group);
for ($i=1 ; $i<=count($chk_group);$i++)
{
$val =$chk_group[$i];
echo "<br>";
echo '<input type="checkbox" value="' . $val . '" name="chk_group">' . $val;
echo "</br>";
}
?>
</div>
<div class="form-group">
Declare new Tags:<br/>
<input type="text" value="" name="tag">
</p>
</div>
<p>
<input type="submit" class="btn btn-success btn-block" value="Post Your Question" id="postQuestion">
</p>
<?php echo form_close();?>
homepage.php (controller)
public function test() {
echo "test";
$name = $this->input->post('tag');
print_r($name);
$des = $this->input->post('decription');
print_r($des);
$data = $this->input->post('chk_group');
var_dump($data);
/* foreach ($this->input->post('chk_group') as $r) {
echo $r;
}
*/
}
You should use array to name the check boxes. You used loop to generate the check boxes & used same name for all. For this you got only last one value.
echo '<input type="checkbox" value="' . $val . '" name="chk_group[]">' . $val;

How to get form input array into PHP array but not empty field

I have a form like the one below which is posted to same page, and the user can dynamically add more textbox with jquery.
<h1> Add Your Order </h1>
<form method="post" action="">
<p id="add_field"><span> Click to Add </span></p>
<div id="container">
<input type="text" class="pid" id="' + counter + '" name="Product[]" />
<input type="text" class="qid" id="' + counter + '" name="Quantity[]" /><br />
</div><br />
<input type= "submit" Name="submit_order" value="Submit">
</form>
everything work fine but if someone add more textbox and leave some textbox as empty then it going to submit. this is my problem i don't want to submit empty textboxes in my table and i want server side solution for this.
Here is my full code with php
<body>
<?php
if ( isset($_POST['submit_order']) ) {
if ( !empty($_POST['Product']) && !empty($_POST['Quantity']) ) {
$product = ($_POST['Product']);
$quantity = ($_POST['Quantity']);
foreach ($product as $id => $value) {
$products = ($product[$id]);
$quantitys = ($quantity[$id]);
$query = mysql_query("INSERT iNTO myorders (product,quantity) VALUES ('$products','$quantitys')", $connection);
}
}
echo "<i><h2><stront>" . count($_POST['Product']) . "</strong> Entry Added </h2></i>";
mysql_close();
}
?>
<?php
if (!isset($_POST['submit_order'])) {
?>
<h1> Add Your Order </h1>
<form method="post" action="">
<p id="add_field"><span> Click to Add </span></p>
<div id="container">
<input type="text" class="pid" id="' + counter + '" name="Product[]" />
<input type="text" class="qid" id="' + counter + '" name="Quantity[]" /><br />
</div><br />
<input type= "submit" Name="submit_order" value="Submit">
</form>
<?php }
?>
</body>
You can use array_filter to get the elements of the arrays that are not empty. If the number of non-empty elements is different from the original array sizes, the user left some fields blank.
$filled_product = array_filter($product);
$filled_quantity = array_filter($quantity);
if (count($filled_product) < count($product) || count($filled_quantity) < count($quantity)) {
// Report error because of unfilled fields
}
Something like this should work:
foreach ($_POST[Product] as $key => $value):
if (empty($value)):
unset($_POST[Product][$key]);
endif;
endforeach;
foreach ($_POST[Quantity] as $key => $value):
if (empty($value)):
unset($_POST[Quantity][$key]);
endif;
endforeach;
Thank you everyone for helping me, unfortunately no one give me a complete solution for this question
but #Wranorn give me a idea and i change my code and yes this solve my question
here is my solution for this
<body>
<?php
if ( isset($_POST['submit_order']) ) {
$product = ($_POST['Product']);
$quantity = ($_POST['Quantity']);
foreach ($product as $id => $value) {
$products = ($product[$id]);
$quantitys = ($quantity[$id]);
if (!empty($products) && !empty($quantitys)) {
$query = mysql_query("INSERT iNTO myorders (product,quantity) VALUES ('$products','$quantitys')", $connection);
}
}
echo "<i><h2><stront>" . count($_POST['Product']) . "</strong> Entry Added </h2></i>";
mysql_close();
}
?>
<?php
if (!isset($_POST['submit_order'])) {
?>
<h1> Add Your Order </h1>
<form method="post" action="">
<p id="add_field"><span> Click to Add </span></p>
<div id="container">
<input type="text" class="pid" id="' + counter + '" name="Product[]" />
<input type="text" class="qid" id="' + counter + '" name="Quantity[]" /><br />
</div><br />
<input type= "submit" Name="submit_order" value="Submit">
</form>
<?php }
?>
</body>

Detecting which form was submitted in php

What would be a reliable way to detect which form was submitted in a situation like below? All submit to the same page, which in turn does things based on which form was submitted. Many drawbacks have been pointed out to the way this is being done. To top it all, even querystrings go to the same script. How would you suggest this be done?
Form one has two input fields, form two has three.
<?php
if ( isset($_POST['valOne']) && isset($_POST['valTwo']) && isset($_POST['valThree']) ) {
echo 'This is form three';
} elseif ( isset($_POST['valOne']) && isset($_POST['valTwo']) ) {
echo 'This is form two';
} else {
echo 'Neither one or two';
}
$formOne = '<form method="post" action="http://localhost/dev/form.php">';
$formOne .= 'Name: <input type="text" name="valOne" value="Foo" autocomplete="off"><br>';
$formOne .= 'Description: <input type="text" name="valTwo" value="Bar" autocomplete="off"><br>';
$formOne .= '<input type="hidden" name="secretVal" value="secretKey">';
$formOne .= '<input value="Add This" type="submit">';
$formOne .= '</form>';
$formTwo = '<form method="post" action="http://localhost/dev/form.php">';
$formTwo .= 'Name: <input type="text" name="valOne" value="Foo" autocomplete="off"><br>';
$formTwo .= 'Description: <input type="text" name="valTwo" value="Bar" autocomplete="off"><br>';
$formTwo .= 'URL: <input type="text" name="valThree" value="Tar" autocomplete="off"><br>';
$formTwo .= '<input type="hidden" name="secretVal" value="secretKey">';
$formTwo .= '<input value="Add This" type="submit">';
$formTwo .= '</form>';
$formThree = '<a href="http://localhost/dev/form.php?do=getIt">This is GET. Get it?<a/>';
echo $formOne;
echo '<br>';
echo $formTwo;
echo '<br>';
echo $formThree;
?>
You could use a hidden input with different names for the 2 forms and on server side you can check with if(isset($_POST['hidden_for_form1'])) or if(isset($_POST['hidden_for_form2'])).
You could add a form_id parameter to the form action.
<form method='post' action='http://localhost/dev/form.php?form_id=1'>
Then in your code switch on $_GET["form_id"];
I'd use hidden inputs
<input type="hidden" name="form" value="form1">
Also on a side note, is there any reason you're storing the form code in a variable?
Add a hidden input:
<input type="hidden" name="form" value="one">
<?switch($_POST['form']){
case "one":
...
?>
You can also assign the name and value to a submit button, but that doesn't work if the user presses enter
You need to assign some name in submit, like:
<input type="submit" name="form1" value="Add This">
<input type="submit" name="form2" value="Add This">
<input type="submit" name="form3" value="Add This">
so..
if(isset($_POST['form1'])){ //do some stuff }
if(isset($_POST['form2'])){ //do some stuff }
if(isset($_POST['form3'])){ //do some stuff }

Can't access array via $_POST

I have the following html code:
<form method="post" action="arrayplay.php">
<input type="checkbox" value="1" name="todelete[]"/>
<input type="checkbox" value="2" name="todelete[]"/>
<input type="checkbox" value="3" name="todelete[]"/>
<input type="checkbox" value="4" name="todelete[]"/>
<input type="submit" value="delete" name="delete"/>
</form>
And the following PHP script:
//arrayplay.php
foreach ($_POST['todelete'] as $id)
{
echo $id . "<br/>";
}
?>
It is supposed to echo out each element value but instead I get an error. I am getting really frustrated. If I use:
<form method="post" action="arrayplay.php">
<?php
$dbc= //connection
$query = "SELECT * FROM email_list";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
echo '<input type="checkbox" value="' . $row['id'] . '" name="todelete[]" />';
echo $row['first_name'];
echo ' ' . $row['last_name'];
echo ' ' . $row['email'];
echo '<br />';
}
mysqli_close($dbc);
?>
<input type="submit" name="submit" value="Remove" />
</form>
It works perfectly fine! Why? The first (hard coded html) holds the exact same value as the one that retrieves them from the database. I am having a real hard time understanding retrieving values from an array with $_POST. Why does name=foo[] create an array? Is it an associative or numeric array? I'm sorry for all of the questions, I'm just really ready to pull my hair out.
if you just named the input foo it would only get one value. because square brackets are commonly used for arrays, foo[] is how in the html form, you indicate an array. of course on the PHP side you just call it foo as you are aware from your working example.
I've tested this and it should work:
<?php
if ($_POST['delete']) {
foreach ($_POST['todelete'] as $id) {
echo $id.' selected<br />';
}
}
?>
<form method="post" action="arrayplay.php">
<input type="checkbox" value="1" name="todelete[]"/>
<input type="checkbox" value="2" name="todelete[]"/>
<input type="checkbox" value="3" name="todelete[]"/>
<input type="checkbox" value="4" name="todelete[]"/>
<input type="submit" value="delete" name="delete"/>
</form>
If you're still having troubles, you can try:
<?php
if ($_POST['delete']) {
for ($i = 0; $i < 4; $i++) {
if (isset($_POST['todelete'][$i])) {
echo $_POST['todelete'][$i].' selected<br />';
}
}
}
?>

Categories