PHP Forms - Numeric Value of Checkbox - php

I am creating an online order form for multiple products. I need to calculate the total cost for the products selected via checkbox and send it as a confirmation e-mail. The value of the checkbox is the price in dollars.
<input type="checkbox" id="product1" name="product1" value="100" />
<input type="checkbox" id="product2" name="product2" value="250" />
In my 'process.php' file, I need to total the cost for all items if they are checked.
if(isset($_POST['product1']) && $_POST['product1'] == '100') {
   $product1 = 100;
}
if(isset($_POST['product2']) && $_POST['product2'] == '250') {
   $product2 = 250;
}
$dollars = $product1 + $product2;
When I try to do it this way, $dollars is an empty variable "". Can someone tell me how to fix this?
Thank you!

There is no syntactical error in your code. So the only explanation is that,
$_POST['product1'] does not have value 100 or they are not sent through post at all
$_POST['product2'] also does not have value 250 or they are not sent through post as well
In order to verify this, do a quick var_dump($_POST) at the top of your .php file

This works, so something does not work in your code but we cant see it right now
<?php
if(isset($_POST['submit']) ) {
if(isset($_POST['product1']) && $_POST['product1'] == '100') {
$product1 = 100;
}
if(isset($_POST['product2']) && $_POST['product2'] == '250') {
$product2 = 250;
}
echo $dollars = $product1 + $product2;
}
?>
<form method="post">
<input type="checkbox" id="product1" name="product1" value="100" />
<input type="checkbox" id="product2" name="product2" value="250" />
<input type="submit" name="submit" />
</form>

You can post an array of checkbox if you want. Try this :
<?php
$dollars = 0;
// If the user post the form
if(isset($_POST['value'])) {
foreach ($_POST['product'] as $product) {
if(is_numeric($product) && $product >= 0) {
$dollars += $product;
}
}
}
?>
<!DOCTYPE HTML>
<html>
<head></head>
<body>
<p>Product : <?php echo $dollars; ?></p>
<form method="post">
<label><input type="checkbox" name="product[]" value="100" /> 100</label><br/>
<label><input type="checkbox" name="product[]" value="250" /> 250</label><br/>
<label><input type="checkbox" name="product[]" value="350" /> 350</label><br/>
<label><input type="checkbox" name="product[]" value="20" /> 20</label><br/>
<label><input type="checkbox" name="product[]" value="25" /> 25</label><br/>
<input type="submit" name="value" />
</form>
</body>
</html>
This code gets an array of selected products and make the sum.

Checkbox values are not sent to the server with POST data if not checked. (edited post)
If you must POST this data, consider using a <input type="hidden" name="product1value" value="100"/> to send the value instead? Keep the check boxes just to see if they are ticked.

Related

Total result for PHP

I have a form built with checkboxes but I am unable to calculate the total result for it. I want to get the total if user selects three checkboxes total will be $3 if one then $1. I am stuck as I am unable to do the calculation.
<html
<head>
<title>Order</title>
</head>
<body>
<link rel= "stylesheet" href= "order.css">
<form action="complete.php" method="post">
<form name="order">
<fieldset><legend>Complete Order:</legend>
<h1> Choose Design </h1>
<p><label>Your Name: <input type="text" name="name"></label>
<label>Address: <input type="text" name="address"></label>
<label>Credit Card #: <input type="text" name="creditcard"></label>
<label>Date: <input type="date" id="datepicker" name='date' size='9' value="" > </label>
<br><label> Design Types: <img src="1.jpg"><input type="checkbox" name="1"></label> $1.00
<label><img src="2.jpg"><input type="checkbox" name="2"> </label>$1.00
<label><img src="3.jpg"><input type="checkbox" name="3"> </label>$1.00
<br></p>
<input type="submit" value="Submit Order">
</form>
</body>
</html>
Php code
<html>
<head>
<title>Form Feedback</title>
</head>
<body>
<?php
if ( !empty($_POST['name']) && !empty($_POST['address']) && !empty($_POST['creditcard']) ) {
echo "<p>Thank you, <strong>{$_POST['name']}</strong>, for placing the order.
<p>Your item will be shipped to:
<tt>{$_POST['address']}</tt></p>
<p>Following credit card has been charged: <em>{$_POST['creditcard']}</em>.</p>\n";
} else { //Missing form value.
echo '<p>Please go back and fill out the form again.</p>';
}
?>
</body>
</html>
Changes in HTML:
<label><img src="1.jpg"><input type="checkbox" name="fieldname[]" value="1"></label> $1.00
<label><img src="2.jpg"><input type="checkbox" name="fieldname[]" value="1"> </label>$1.00
<label><img src="3.jpg"><input type="checkbox" name="fieldname[]" value="1"> </label>$1.00
PHP Code: it will count number of selected checkboxes-
<?php
if(isset($_POST['fieldname']) && !empty($_POST['fieldname'])){
echo count($_POST['fieldname']); //count the number of selected checkbox
echo array_sum($_POST['fieldname']); //sum of selected checkbox values
}
?>
Use isset($_POST['checkboxName']) to check if the checkbox is checked and then add 1 for each checkbox:
$check_value = 0;
$check_value += isset($_POST['1']) ? 1 : 0;
$check_value += isset($_POST['2']) ? 1 : 0;
$check_value += isset($_POST['3']) ? 1 : 0;
Change the php part:
<?php
if ( !empty($_POST['name']) && !empty($_POST['address']) && !empty($_POST['creditcard']) ) {
$cost = 0;
if(isset($_POST['1'])) $cost += 1;
if(isset($_POST['2'])) $cost += 1;
if(isset($_POST['3'])) $cost += 1;
echo "<p>Thank you, <strong>{$_POST['name']}</strong>, for placing the order.
<p>Your item will be shipped to:
<tt>{$_POST['address']}</tt></p>
<p>Following credit card has been charged: <em>{$_POST['creditcard']}</em>.</p>
<p>With amount: <em>{$cost}</em>.</p>\n";
} else { //Missing form value.
echo '<p>Please go back and fill out the form again.</p>';
}
?>
First of all, it's about checkbox's name. If they are a group of values (e.g: products), use a common name as an array:
<input type="checkbox" name="product[]" />
<input type="checkbox" name="product[]" />
<input type="checkbox" name="product[]" />
The second question, shouldn't your checkbox has a value or it'll be always $
1.00?
It it'll be always $1.00, just count it:
$value = isset($_POST['product']) ? count($_POST['product']) : 0;
If it should has a value:
<input type="checkbox" name="product[]" value="1.00" />
<input type="checkbox" name="product[]" value="1.50" />
<input type="checkbox" name="product[]" value="2.00" />
Can use the array_sum function:
$value = isset($_POST['product']) ? array_sum($_POST['product']) : 0;

how to save multiple radio button in database using php without save button value

how to save multiple radio button in database using php without save button value.
my code :
$user_id = $_POST['user_id'];
foreach ( $_POST as $key => $val ) {
if ($key <> 'user_id') {
$bidder_interst_insert="INSERT INTO bidder_interest_list(id, bidder_id, bidder_interest_name) VALUES ('','$user_id','$val')";
$bidder_interst_insert_result = mysql_query($bidder_interst_insert);
if (mysql_affected_rows() > 0) {
$interest_list_success = "Thank you Successfull insert your interst list.";
$_SESSION['interest_list_success_msg'] = $interest_list_success;
} else {
$insert_error = "interst list Insert Error.";
$_SESSION['insert_error_msg'] = $insert_error;
header("location:interest_list.php");
}
}
}
This code work but database extra save in save button value how to solved this problem??
foreach ( $_POST as $key => $val ){
You are directly looping the $_POST, so the SAVE button value is also saving in the database. Take the values individually instead of looping the whole $_POST, then the SAVE button value won't be saved in the database.
And moreover you are using mysql functions which are deprecated, use mysqli or PDO.
EDIT::
Just take it the same way as u took user_id ==> $variablename = $_POST['fieldname'];
EDIT:::
Let me suppose i have a form like this
<form name="form1" id="form1" method="post" action="">
<input type="checkbox" name="products[]" value="A" checked="checked" />A <br />
<input type="checkbox" name="products[]" value="B" checked="checked" />B <br />
<input type="checkbox" name="products[]" value="C" checked="checked" />C <br />
<input type="checkbox" name="products[]" value="D" checked="checked" />D <br />
<input type="checkbox" name="products[]" value="E" checked="checked" />E <br />
<input type="checkbox" name="products[]" value="F" checked="checked" />F <br />
<input type="submit" name="save" id="save" value="Save" />
</form>
then i can do it like:
<?php
if(isset($_POST['save']))
{
$products = $_POST['products'];
foreach($products as $key => $value)
{
$qry = mysql_query("INSERT INTO tbl(product) VALUES('$value')");
}
}
?>
Try this
unset($_POST['name-of-save-button']);
$data = $_POST;
foreach ( $data as $key => $val ){//your code here}

Save $_SESSION from a list of checkbox data?

Im trying to save $_SESSION data to keep checked values on page refresh, I have some code written up but I am missing a piece.
Session Code:
session_start();
if(isset($_POST['submit'])) {
//user posted variable
$checks = $_POST['personalization_result'];
if(isset($_POST['personalization_result'])) {
$_SESSION['value'] = $_POST['personalization_result']; }
else {
$_SESSION['value'] = '';
}
}
Form Code:
<form action="" method="post" id="question-form">
<input type="hidden" name="submit" value="1">
<li>
<input name="personalization_result[memory_0]" type="hidden" class="<?php echo $_SESSION['value']['memory_0'] ?>" value="0" />
<input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" />
</li>
<li>
<input name="personalization_result[memory_1]" type="hidden" class="<?php echo $_SESSION['value']['memory_1'] ?>" value="0" />
<input name="personalization_result[memory_1]" type="checkbox" value="1" id="personalization_result_memory_1" />
</li>
//There are many checkboxes, this is just two for demo purposes
<input class="submit" type="submit" value="Send" />
</form>
For testing I am echoing $_SESSION['value']['memory_0'] && $_SESSION['value']['memory_1']inside the hidden input, they return properly, if the input is checked the class is 1, if it's unchecked the class is 0.
I am not sure the best way to say if it = 1 then echo checked="checked"
My shotty attempt:
<input name="personalization_result[memory_0]" type="hidden" class="<?php echo $_SESSION['value']['memory_0'] ?>" value="0" />
<input name="personalization_result[memory_0]" type="checkbox" value="1" id="personalization_result_memory_0" <?php if($_SESSION['value']['memory_0'] = 1) {echo 'checked="checked"';} ?> />
This returns an error "Cannot use a scalar value as an array", that and I dont like how thats written up.
So with all the given information, whats the best way to write if my value = 1 return checked="checked"?
This will make your PHP much cleaner and scalable:
Use this function at the top:
session_start();
function checkbox($id)
{
$isChecked = '';
if (isset($_SESSION['value']['memory_'.$id]))
{
$isChecked = ($_SESSION['value']["memory_".$id] == 1) ? 'checked="checked"' : '';
}
echo '<input name="personalization_result[memory_'.$id.']" type="checkbox" ';
echo 'value="1" id="personalization_result_memory_'.$id.'" ';
echo $isChecked.' />';
}
and then instead of writing out <input ... <?php ... ?> ... /> for every single checkbox, just use
<?php checkbox(0); ?>
<?php checkbox(1); ?>
Your short attempt has an error:
instead of <?php if($_SESSION['value']['memory_0'] = 1) try <?php if($_SESSION['value']['memory_0'] == 1)

keeping radio button value after post

HI
i'm using a php page and i need to keep the value of and check box and radio button (checked or not checked) after post page.
how could i make it?
thanks
First get the radio button value.
$radiobuttonvalue = $_POST['radiobuttoname']
Then for each radio button with the same name, do this
<input type="radio" name="radiobuttonname" value="value" id="radiobuttonname" <?php if($radiobuttonvalue == "value") { echo 'checked="checked"';} ?>
You need something like:-
<?php
$postCheckboxName = '';
if (isset($_POST['checkbox_name']) || 'any_value' == $_POST['checkbox_name']) {
$postCheckboxName = ' checked="checked"';
}
?>
<input type="checkbox" name="checkbox_name" value="any_value"<?php echo $postCheckboxName;?> />
<?php
$postRadioName = '';
if (isset($_POST['radio_name']) || 'any_other_value' == $_POST['radio_name']) {
$postRadioName = ' checked="checked"';
}
?>
<input type="checkbox" name="radio_name" value="any_other_value"<?php echo $postRadioName;?> />
This code should get you going. I'm basically checking whether the POST value of either the checkbox / radio element is set or not & whether the corresponding element's value matches with my respective element's value or not.
Hope it helps.
Something like this:
<?php if (isset($_POST['checkbox_name']))?>
<input type="checkbox" checked="checked" value="<?php echo $_POST['checkbox_name'];?>" />
<?php} ?>
<?php if (isset($_POST['radio_name']))?>
<input type="radio" checked="checked" value="<?php echo $_POST['radio_name'];?>" />
<?php} ?>
What happens is that you check if the input variables are in the $_POST and if so you add checked="checked" to the input fields to make them checked.
This worked for me, and is self explanatory
sample code usage:
<div class="form-group">
<label class="radio-inline">
<input type="radio" name="time" value="lunch" <?php if (isset($_POST[ 'time']) && $_POST[ 'time']=='lunch' ){echo ' checked="checked"';}?>>Lunch</label>
<label class="radio-inline">
<input type="radio" name="time" value="dinner" <?php if (isset($_POST[ 'time']) && $_POST[ 'time']=='dinner' ){echo ' checked="checked"';}?>>Dinner</label>
</div>

How do I see which checkbox is checked?

How do I check in PHP whether a checkbox is checked or not?
If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.
if (isset($_POST['mycheckbox'])) {
echo "checked!";
}
you can check that by either isset() or empty() (its check explicit isset) weather check box is checked or not
for example
<input type='checkbox' name='Mary' value='2' id='checkbox' />
here you can check by
if (isset($_POST['Mary'])) {
echo "checked!";
}
or
if (!empty($_POST['Mary'])) {
echo "checked!";
}
the above will check only one if you want to do for many than you can make an array instead writing separate for all checkbox try like
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
php
$aDoor = $_POST['formDoor'];
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($aDoor);
echo("You selected $N door(s): ");
for($i=0; $i < $N; $i++)
{
echo htmlspecialchars($aDoor[$i] ). " ";
}
}
Try this
index.html
<form action="form.php" method="post">
Do you like stackoverflow?
<input type="checkbox" name="like" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
form.php
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['like']))
{
echo "<h1>You like Stackoverflow.<h1>";
}
else
{
echo "<h1>You don't like Stackoverflow.</h1>";
}
?>
</body>
</html>
Or this
<?php
if(isset($_POST['like'])) &&
$_POST['like'] == 'Yes')
{
echo "You like Stackoverflow.";
}
else
{
echo "You don't like Stackoverflow.";
}
?>
If you don't know which checkboxes your page has (ex: if you are creating them dynamically) you can simply put a hidden field with the same name and 0 value right above the checkbox.
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">
This way you will get 1 or 0 based on whether the checkbox is selected or not.
I love short hands so:
$isChecked = isset($_POST['myCheckbox']) ? "yes" : "no";

Categories