user2953877
user2953877

Reputation: 43

Add value of the check box to PHP result?

I have a PHP shopping cart which is very simple and it works as it should.

However what i want to do is to add two checkboxes in the shopping cart with two different values for shipping costs.

for example one has a value of 7 and one has a value of 12.

I have this PHP in my shopping cart:

$totalAll = $totalAll + ($item['qty']*$item['price']) + 'ship';

And i echo the $totalAll like this:

<?php echo $totalAll;?>

I have these two checkboxes too:

<label>UK Shipping</label>
<input name="ship" type="checkbox" value="7" />

    <label>International Shipping</label>
<input name="ship" type="checkbox" value="12" />

so I need the $totalAll + 'ship' value but the way i did it doesn't really make sense!

could someone help me out with this please?

Thanks

Upvotes: 0

Views: 227

Answers (4)

Philipp
Philipp

Reputation: 15629

I'd suggest you to use radio buttons instead of check boxes and store the shipping values on the server. This results in something like this:

$shipping = array(
    1 => 7,
    2 => 12
);

// nothing selected?
if (!isset($_REQUEST['ship'])) {
    die("error"); // your error handling..
}
$ship = $shipping[(int) $_REQUEST['ship']];

and the html

<label>UK Shipping</label>
<input name="ship" type="radio" value="1" />

<label>International Shipping</label>
<input name="ship" type="radio" value="2" />

Upvotes: 0

dap.tci
dap.tci

Reputation: 2485

You can use radio instead of checkbox:

<label for="uk">UK Shipping</label>
<input id="uk" name="ship" type="radio" value="7" />

<label for="international">International Shipping</label>
<input id="international" name="ship" type="radio" value="12" />

Upvotes: 0

Realit&#228;tsverlust
Realit&#228;tsverlust

Reputation: 3953

First of all, i would recommend radio buttons. It doesnt make sense to add both kinds of shipping costs.

Second, adding "ship" to a number wont help you. You need the following in your receiveform (in my case test.php):

HTML:

<form method="post" action="test.php" enctype="multipart/form-data">
    <input type="radio" name="ship" value="7">
    <input type="radio" name="ship" value="12">
    <input type="submit">
</form>

test.php:

$ship = $_POST['ship'];
$total = $totalAll + $ship;

This will give you the full price.

Dont forget to validate input! In general, its not a good practice to rely on the HTML form for calculating prices.

Upvotes: 1

Yami
Yami

Reputation: 1425

HTML

<label>UK Shipping</label>
<input name="ship[]" type="checkbox" value="7" />

    <label>International Shipping</label>
<input name="ship[]" type="checkbox" value="12" />

PHP

   $ship = 0;
   foreach($_POST['ship'] as $s)
   {
      $ship += $s;
   }
   $totalAll += ($item['qty']*$item['price']) + $ship;

Upvotes: 1

Related Questions