tags:

views:

65

answers:

2

I looking to sum three values of the price field if selected.

$sql = "SELECT * FROM shoes
    WHERE tray on tray.product_id = shoes.id";
 $sth = mysql_query($sql);
 $variety = mysql_fetch_array($sth)) {
echo'<div>
<p>'. $variety['name']. '</p>
<p class="price">'. $variety['price']. '</p>
<input name="price" type="checkbox" value=""  />
</div>
<div>
<p>'. $variety['name']. '</p>
<p class="price">'. $variety['price']. '</p>
<input name="price" type="checkbox" value=""  />
</div>
<div>
<p>'. $variety['name']. '</p>
<p class="price">'. $variety['price']. '</p>
<input name="price" type="checkbox" value=""  />
</div>
}

if you notice each iteration will have a checkbox input and users can choose one or the three if they one. Now how can I sum how if user chooses more than one price?

+1  A: 

In your form, you want PHP to treat your input as an array, so change your HTML like so-> add [] after the name.

<input name="price[]" type="checkbox" value=""  /> 

Then in PHP just access the form variable name like you normally would and loop through the values and sum them.

chamiltongt
+1  A: 

Add brackets after each of the price names to tell PHP that price should be an array:

<input name="price[]" type="checkbox" value=""  />

Then in PHP you will get the variable $price (which will be an array) and sum all of its values (it will only contain the checked values). Something like:

<?php
  $price = $_POST['price'];
  $total = 0;

  foreach( $price as $p )
  {
     $total += $p;
  }
?>
Josh Curren
a more efficient way would be to use array_sum()
Ben Rowe
Will I need to declare $price=array; at the beggining?
jona
@jona No, $_POST['price'] is giving $price an array.
Josh Curren
@Ben Yes, but since he is a beginner it cant hurt to learn how to iterate through an array.
Josh Curren
There is an argument which is failing and it's probably the definition of price which fails at the foreach. The code below is a representatino of what I have don't know what's could be wrong int he set up.foreach($product['varieties'] as $variety){ <p>' . $variety['price']. '</p><p class="price">' . $variety['price']. '</p>$price = $variety['price']; $total = 0; foreach( $price as $p ) { $total += $p; }echo $total;}Error is as: Warning: Invalid argument supplied for foreach() in /home3/stores/public_html/example2.php on line 3030
jona
Your $price = $variety['price']; is wrong. It should be just he way I have it in my example... naming all checkboxes price[] will create an array.
Josh Curren
ok what about this code<?php $price = $_POST['price']; $total = 0; foreach( $price as $p ) { $total += $p; }?>do you use it in the page where the form action send the user?
jona
action="cart.php"? in cart.php?
jona
the code looks right... you put that code in cart.php..... You really should read the PHP Tutorial at w3 school http://www.w3schools.com/php/default.asp
Josh Curren