how to add up values from checkboxes in php - php

for training purposes i've made a little code which outputs the value of a checkbox. this works well, but since i am able to check multiple checkboxes i want them to add up. this is my code;
<table border=0 cellpadding=0 cellspacing=0 width=100%>
<form name="orderform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="checkbox" name="korting" value=15 /> Student 15% <br>
<input type="checkbox" name="korting" value=10 /> Senior 10% <br>
<input type="checkbox" name="korting" value=5 /> Klant 5% <br>
To output the value ive written;
<?php
if(isset($_POST["korting"]))
{
if($_POST["korting"]==15)
{
echo ("15 procent korting");
}
else if ($_POST["korting"]==10)
{
echo ("10 procent korting");
}
else if($_POST["korting"]==5)
{
echo ("5 procent korting");
}
else if(isset($_POST["korting"]) && (isset($_POST["korting"])))
{
if($_POST["korting"]==25)
{
echo ("25 procent korting");
}
}
}
?>
As long as one checkbox is checked, everything works fine. as soon as is check more than one it only uses the last one. I've tried multiple thing like:
else if(isset($_POST["korting"]) && (isset($_POST["korting"]))
{
echo ("25 procent korting");
}
and
else if($_POST["korting"=15] && $_POST["korting"]=10)
{
echo ("25 procent korting");
}
both do not give an error on the page but also don't work. I know it's probably better to use completely different approach but for now this is how the book teaches me
Greetings,
Lennart

What you need is an array. The checkboxes would look like this:
<input type="checkbox" name="korting[]" value="15" />
<input type="checkbox" name="korting[]" value="10" />
$_POST['korting'] would then be an array of values, like this:
array(
0 => 15,
1 => 10
)
You can loop through them to print out the values:
foreach ($_POST['korting'] as $korting_value) {
echo $korting_value . "<BR>";
}
If you want to add up the values, you can use array_sum:
echo array_sum($_POST['korting']);

Related

I am trying to identify multiple values which were selected from a checkbox using PHP

I am trying to identify multiple values which were selected from a checkbox using PHP, here is my code below, you can see i have attempted to create a custom string when Java and C/C++ is selected
<form action="#" method="post">
<input type="checkbox" name="check_list[]" value="C/C++"><label>C/C++</label><br/>
<input type="checkbox" name="check_list[]" value="Java"><label>Java</label><br/>
<input type="checkbox" name="check_list[]" value="PHP"><label>PHP</label><br/>
<input type="submit" name="submit" value="Submit"/>
</form>
<?php
if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected){
echo $selected."<br>";
}
}
}
if(in_array('C/C++', $_POST['check_list'])) {
echo 'C/C++ was checked!';
} elseif(in_array('C/C++','Java',$_POST['check_list'])){
echo 'C/C++ and Java was checked!';
}
?>
You can't give multiple needles to in_array().
Also, if both C/C++ and Java are selected, the first if will succeed, so it will never try the elseif. If you want a structure like that, you need to test the larger group first.
You can use nested if instead.
if(in_array('C/C++', $_POST['check_list'])) {
if (in_array('Java', $_POST['check_list'])) {
echo 'C/C++ and Java were checked!';
} else {
echo 'C/C++ was checked!';
}
}
A more general way to test if multiple items are in the array is with array_intersect:
if (!empty(array_intersect(['C/C++', 'Java'], $_POST['check_list'])) {
echo 'C/C++ and Java were checked!';
}

Using the output of a form that is already appearing based on a previous condition for a calculation

I am writing code for a running pace calculator, if there is any wind you have the option of factoring this into your calculation altering the time depending on if its a headwind or a tailwind
Part of HTML:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>"
method="POST">
<input type="checkbox" id="windspeed" name="windspeed" value="windspeed">
<label for="windspeed">Any Wind?</label></p>
PHP SCRIPT:
So this part of the PHP works, its creates all of the fields with the values I need to calculate pace lost/gained in headwind tailwind:
$max=($_POST['distance']/$_POST['laplength']);
if (!empty($_POST['windspeed'])&&(empty($_POST['elevation'])))
{
echo "<p><label for=\"Windspeedvalue\">Wind Speed (mph): </label>
<input type=\"number\" id=\"Windspeedvalue\" name=\"Windspeedvalue\"></p> <br/>
<label for=\"height\">Height(cm):</label><input type=\"number\" id=\"height\" name=\"height\"></p><br/>
<label for=\"weight\">Weight(Kg):</label><input type=\"number\" id=\"weight\" name=\"weight\"></p><br/>";
$counter=1;
while($counter<=$max)
{
if (!empty($_POST['windspeed'])&&(empty($_POST['elevation'])))
{
echo "<br/>
<label for=\"WindDirection\">Lap $counter:</label>
<select name=\"WindDirection\">
<option value=\"\">Wind Direction...</option>
<option value=\"Tailwind $counter\">Tailwind</option>
<option value=\"Headwind $counter\">Headwind</option>
</select>";
$counter++;
}
echo"<input type=\"hidden\" name=\"Winddirectionhidden\" value=\"Winddirectionhidden\"><br/>";
}
echo "<br/>";
}
elseif (!empty($_POST['windspeed'])&&(!empty($_POST['elevation'])))
{
echo "<p><label for=\"Windspeedvalue\">Wind Speed (mph): </label>
<input type=\"number\" id=\"Windspeedvalue\" name=\"Windspeedvalue\"></p><br/>
<label for=\"height\">Height(cm):</label><input type=\"number\" id=\"height\" name=\"height\"></p><br/>
<label for=\"weight\">Weight(Kg):</label><input type=\"number\" id=\"weight\" name=\"weight\"></p><br/>";
}
However, when I try to use this to alter the pace in the output table. It only reads in the header title, its not reaching the echo TEST values so I know its something to do with the second if/elseif statement or after the wind direction is set.
if (!empty(($_POST['Windspeedvalue'])&&($_POST['Winddirectionhidden'])))
{
$max=$_POST['distance']/$_POST['laplength'];
$totalseconds=($_POST['minutes']*60)+($_POST['seconds']);
$paceinseconds=$totalseconds/$max;
$maxint=(integer)$max;
$pacelost=$_POST['Windspeedvalue']*$_POST['Height']*$_POST['Weight']*1.275;
$pacegained=$_POST['Windspeedvalue']*$_POST['Height']*$_POST['Weight']*(1.275/2);
$totalflattime=$totalseconds-$pacelost+$pacegained;
$flattimeperlap=$totalflattime/$_POST['distance'];
$laptimeinheadwind=$flattimeperlap-($pacelost/$_POST['distance']);
$laptimeintailwind=$flattimeperlap+($pacegained/$_POST['distance']);
echo "<table>";
echo "<tr><th>Lap Number</th><th>Time</th></tr>";
for($counter=1;$counter<=$maxint;$counter++)
{
if(isset($_POST['WindDirection']))
{
$tempperunitseconds=$unitpace*$counter;
$tempminutes=($tempperunitseconds/60);
$outminutes=(integer)$tempminutes;
$outseconds=(integer)(($tempminutes-$outminutes)*60);
printf("<tr><td>%02s</td><td>%02s.%02s</td></td>",$counter,$outminutes,$outseconds);
}
$direction=$_POST['WindDirection'];
if($direction=="Headwind")
{
echo 'TEST1';
$tempperunitseconds=$laptimeintailwind*$counter;
$tempminutes=($tempperunitseconds/60);
$outminutes=(integer)$tempminutes;
$outseconds=(integer)(($tempminutes-$outminutes)*60);
printf("<tr><td>%02s</td><td>%02s.%02s</td></td>",$counter,$outminutes,$outseconds);
}
elseif($direction=="Tailwind")
{
echo 'TEST2';
$tempperunitseconds=$laptimeinheadwind*$counter;
$tempminutes=($tempperunitseconds/60);
$outminutes=(integer)$tempminutes;
$outseconds=(integer)(($tempminutes-$outminutes)*60);
printf("<tr><td>%02s</td><td>%02s.%02s</td></td>",$counter,$outminutes,$outseconds);
};
}
echo "</table>";
}
I'm not into PHP but isn't the problem in the value attribute of your WindDirection? In the value you have probably 'Headwind/Tailwind X' but your if statement tries to compare it with 'Headwind/Tailwind'. Not sure which of these is correct but you need to do one of following
Change the value attribute of your option element
Change the if statement to do equality comparison with 'Headwind/Tailwind $counter' or based on 'startsWith' logic
Anyway at the beginning you could try to echo $direction before if statements to find out the real value.

Relating values in a PHP multiple checkbox array

I searched and can't find an answer to this and nothing I try works. In this form, for each image (pix) and there the user enters the number of copies to be produced.
I know how to build the array for each individually when the submit button is clicked but I can't get both arrays to relate to each other. I want to produce something like: 01.jpg - 3 copies, 02.jpg - 1 copy etc etc.
How can I achieve this?
Thanks
This is my form:
<form action="self.php" method="post">
<img src="01.jpg" alt="01.jpg">
<input type="checkbox" name="pix[]" value="01.jpg_album">
<input type="text" name="quantity[]">
<img src="02.jpg" alt="02.jpg">
<input type="checkbox" name="pix[]" value="02.jpg_extra">
<input type="text" name="quantity[]">
<img src="03.jpg" alt="03.jpg">
<input type="checkbox" name="pix[]" value="03.jpg_extra">
<input type="text" name="quantity[]">
<input type="submit" name="submit">
</form>
This is how I extract the values returned:
echo implode('<br>', $_POST['pix']);
echo implode('<br>', $_POST['quantity']);
EDITED: FURTHER to my question above and in response to the second code posted by Rajdeep ... I've separated the two processes. The first was to determine whether the client wanted the image for his wedding album, so I did:
$arr = array("01", "02", "03");
echo "<h3>Images required for album: </h3>";
foreach($_POST as $key => $value){
if(in_array($key, $arr)){
$var = $value . ".jpg";
if(isset($_POST[$value]) && !empty($_POST[$value])){
echo $var."<br />";
}//endif
} //endif
}// end foreach
This output was:
03.jpg
04.jpg
23.jpg
etc
Then, I wanted to know if he needed any additional individual prints and this code (sort of) worked for that:
echo "<h3>Extras required: </h3>";
$noextras = false;
foreach($_POST as $key => $value){
if(in_array($key, $arr)){
$var = $value . ".jpg - ";
if(isset($_POST[$value . "_extra"]) && !empty($_POST[$value . "_extra"])){
$sum = $_POST[$value . '_extra'];
if($sum == 1) {
$var .= $sum ." copy <br />";
} else {
$var .= $sum . " copies <br />";
}
echo $var;
} else if(empty($_POST[$value . "_extra"])) { $noextras = true; }
} //endif in_array
}// end foreach
if($noextras) { echo "No extra copies needed.";}
And the output from this was something like
03.jpg - 5 copies
04.jpg - 2 copies
23.jpg - 1 copy
I then discovered a snag. This permitted extra copied to be selected for ONLY for images that were selected for inclusion in the album. I have tried various variations on the code and I am coming up with a blank.
So, I've changed this to a two step process. First page, the person selects the images for the album, which when submitted go to a confirmation page to show what had been selected. Once he clicks the 'confirm' button an email goes to me and him.
Clicking the confirm button also goes to a Thank You page which then refreshes into the second page for ordering individual prints. Here he can select how many copies of a print he needs and this works well with Rajdeep's first 'merged' code BUT it only works for one selection.
I've expanded the selection and this is where I am currently having trouble. He has a choice to decides how many copies he needs of each of the four different sizes available (7x6, 9x5, 10x8, 12x8). I am able to process one size only but am having trouble with expanding it to four inputs.
Any suggestions?
Thanks.
Instead of two different <input> tags with checkbox and text attribute, use only one <input> with number attribute for each image. And make the name attribute as the name of your image, like this:
<form action="self.php" method="post">
<img src="01.jpg" alt="01.jpg" />
<input type="number" name="01" min="0" />
<img src="02.jpg" alt="02.jpg" />
<input type="number" name="02" min="0" />
<img src="03.jpg" alt="03.jpg" />
<input type="number" name="03" min="0" />
<input type="submit" name="submit" value="submit" />
</form>
And this is how you can process the form,
if(isset($_POST['submit'])){
foreach($_POST as $key => $value){
if($key == "submit"){
continue;
}
if(!empty($value)){
$var = $key . ".jpg - " . $value;
if($value == 1){
$var .= " copy";
}else{
$var .= " copies";
}
$var .= "<br />";
echo $var;
}
}
}
A sample output would be like this:
01.jpg - 3 copies
02.jpg - 1 copy
03.jpg - 5 copies
Edited:
Based on your requirement, use <input type="checkbox" name="xx" value="xx" /> for selecting the image(i.e when user wants this image to be included in photo album) and use <input type="number" name="xx_extra" min="1" /> for keeping track of how many extra copies of this image user wants.
So your HTML code should be like this:
<form action="self.php" method="post">
<img src="01.jpg" alt="01.jpg" />
<input type="checkbox" name="01" value="01" />
<input type="number" name="01_extra" min="1" />
<img src="02.jpg" alt="02.jpg" />
<input type="checkbox" name="02" value="02" />
<input type="number" name="02_extra" min="1" />
<img src="03.jpg" alt="03.jpg" />
<input type="checkbox" name="03" value="03" />
<input type="number" name="03_extra" min="1" />
<input type="submit" name="submit" value="submit" />
</form>
And this is how you can process the form,
<?php
if(isset($_POST['submit'])){
$arr = array("01", "02", "03");
foreach($_POST as $key => $value){
if(in_array($key, $arr)){
$var = $value . ".jpg - ";
if(isset($_POST[$value . "_extra"]) && !empty($_POST[$value . "_extra"])){
$sum = $_POST[$value . '_extra'] + 1;
$var .= $sum . " copies <br />";
}else{
$var .= "1 copy <br />";
}
echo $var;
}
}
}
?>

Insert Multiple data to mysql using a loop ...

so i have this code fragment here..
if($numTF > 0)
{
echo "TRUE-AND-FALSE QUESTIONS: Enter them below followed by their correct answer.";
echo "<br>";?>
<form method="post" action="" name="quizform">
<?php for ($i=1; $i<=$numTF; $i++)
{
echo "Question"." ".$i;
?>`
<p><textarea name='question<?php echo $i; ?>' rows=3 cols=90></textarea></p>
<input type="radio" name="answer<?php echo $i; ?>" value="True"> True
<input type='radio' name="answer<?php echo $i; ?>" value="False"> False<br><br><br>
<?php
}
}
... i am making a quiz maker in php...
the first thing to do is to set up the desired number of questions, so the value entered will go on the $numTF variable. Depending on the entered value, the textarea part will be printed. and there will be different names for each text area. AND THE CODE ABOVE IS WHERE U PRINT THE FORMS AFTER U ENTER THE DESIRED VALUE.
The next thing is to save that in a database. since the name of each textarea will be based on a variable value($i) that is used in a loop (name="answer") , HOW CAN I USE IT IN $_POST??? Like, would i do it like this?? ($_POST['question']).
HOW CAN I SAVE THESE QUESTIONS IN A DATABASE??
PLEASE HELP ME ....
I WOULD BE SO MUCH MUCH MUCH GRATEFUL FOR A LIL HELP.
<?
var_dump($_POST);
?>
<form method="post">
<?
$numTF=4;
if($numTF > 0)
{
echo "TRUE-AND-FALSE QUESTIONS: Enter them below followed by their correct answer.";
echo "<br>";?>
<form method="post" action="" name="quizform">
<?php for ($i=1; $i<=$numTF; $i++)
{
echo "Question"." ".$i;
?>`
<p><textarea name='question[<?php echo $i; ?>]' rows=3 cols=90></textarea></p>
<input type="radio" name="answer[<?php echo $i; ?>]" value="True"> True
<input type='radio' name="answer[<?php echo $i; ?>]" value="False"> False<br><br><br>
<?php
}
}
?>
<input type="submit" name="submit" value="submit"/>
</form>
Use $_POST['question'][1] // To get first question
Use $_POST['answer'][1] // To get first answer
Use loop to get all question and answers
I agree with Sachin as far as using name='question[]'. To answer question a little more as far as storing it in a database. Personally I would use a JSON array.
$store_answers = json_encode($_POST['answer']);
$store_questions = json_encode($_POST['question']);
Then just store $store_string in a TEXT field in your database. Then when you pull it back out of the database you can simple use:
$answers = json_decode($store_answers);
$questions = json_decode($store_questions);
Then you can loop through using a foreach like so:
foreach($questions as $key=>$question) {
echo "Question $key = {$answers[$key]} <br />";
}
This will display the results for each question.

PHP if statement with checkbox error

Sorry for the dumb question, though I'm a little new to PHP.
I've tried a lot of other ways to do this, but simply couldn't get this to work... Actually I want it to make it that I can have different functions attached to each checkbox that when a user selects a checkbox or another, and clicks the submit button, it triggers the specific functions. But I cannot get the checkboxes to work. It either works with only one selected, or if I check the 1st one then the 4th one, it outputs the 4th's code.
Any other ways of doing this?
Here is my attempt:
1.php
<form method="POST" action="2.php">
<input type="checkbox" name="test[]" value="test1" />test1<br />
<input type="checkbox" name="test[]" value="test2" />test2<br />
<input type="submit" name="submit" value="submit" />
</form>
2.php
$val = $_POST['test'];
if(isset($val)==true){
for($i = 0 ; $i<count($val) ; $i++){
if($val=='test1'){
echo $val;
die();
}elseif($val=='test2'){
echo $val;
die();
}else{
echo "fail";
die();
}
}
}else{
return false;
}
Thank you.
Try:
$vals = $_POST['test'];
$valsCount = count($vals);
if ($valsCount > 0) {
foreach ($vals as $val) {
switch ($val) {
case 'test1':
echo $val;
break;
case 'test2':
echo $val;
break;
default:
echo 'Fail';
break;
}
}
}
As another option, if you're looking to call functions based on the value of the checkbox, you could do something like this ...
I've compressed it all into one file for simplicity, but this is the general idea ...
<form method="post" action="<?php echo $_SREVER['PHP_SELF']; ?>">
<input type="checkbox" name="boxes[]" value="box1">Box 1</input><br />
<input type="checkbox" name="boxes[]" value="box2">Box 2</input><br />
<input type="checkbox" name="boxes[]" value="box3">Box 3</input><br />
<input type="checkbox" name="boxes[]" value="box4">Box 4</input><br />
<input type="checkbox" name="boxes[]" value="box5">Box 5</input><br />
<input type="submit" value="Go!" />
</form>
<?php
class boxProcessor
{
public function box1()
{
echo "<p>You've found box 1.</p>";
}
public function box2()
{
echo "<p>You've found box 2.</p>";
}
public function box3()
{
echo "<p>You've found box 3.</p>";
}
public function box4()
{
echo "<p>You've found box 4.</p>";
}
public function box5()
{
echo "<p>You've found box 5.</p>";
}
}
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$boxes = $_POST['boxes'];
if(empty($boxes)){
echo "<p>Nothing to do ...</p>";
} else {
$proc = new boxProcessor();
foreach($boxes as $box){
$proc->$box();
}
}
}
?>
You're pretty close with your code as is, you just have to take into account array indexes.
for ($i = 0, $length = count($val); $i < $length; $i++)
{
// add [$i] to $val to access an index of $val
if ($val[$i] == 'test1')
Try changing the names from test1[] to test1 in 1.php and also check a typo on line 7- 2.php.
Hope this helps.
There are a couple of issues that probably don't have anything to do with the real problem:
1) You talk about "1st" and "4th" checkboxes ... but your code only shows two checkboxes
2) Your example misspells "tes2" (so PHP won't/can't find it)
3) You should probably get rid of all the "die()" clauses
SUGGESTION:
Check out this link:
http://www.html-form-guide.com/php-form/php-form-checkbox.html

Categories