Forum Moderators: coopster

Message Too Old, No Replies

Finding Product Totals Based on Radio Button Selections

         

jiji

4:24 pm on Feb 8, 2007 (gmt 0)

10+ Year Member



Hello everyone i was wondering if someone could help me Im new into php scripts I got a form in wich is a multi page form wich currently is working ok i got it to connect and to show in every page what the user has selected so far in the form.

Now my problem is i want to assign a price for every product and then let the script add the price of the products selected! and show the total price!

<input type="radio" name="product1" value="product a"/>
<input type="radio" name="product1" value="product b" />
<input type="radio" name="product1" value="product c" />

the value i have is for the product name to appear in the next page, now how could i add price for every product and then add them to give a total price.

thanks in advance!

cameraman

6:26 pm on Feb 8, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld, jiji!

You can put the product names and prices into an array. With many languages, an array index has to be a number. php does its arrays a little differently and allows you more freedom with your indexes:
$prices['product a'] = 15;

That line declares $prices to be an array and the element indexed by product a is set to 15. To set more than one at a time, here's the syntax:
$prices = array("product a" => 15, "product b" => 20, "product c" => 30);

Now if you were to echo one:
echo $prices['product b'];

You'd get 20.
Now let's say that someone selected product b on your form. So if you're using method="post" on your form you now have:
$_POST['product1'] = 'product b'

You can do this:
echo $prices[$_POST['product1']]

and you'll still get 20. So,
$total = $prices[$_POST['product1']] + $prices[$_POST['product2']] + $prices[$_POST['product3']] + $prices[$_POST['product4']];

A much more thorough explanation of arrays:
[php.net ]

jiji

11:42 pm on Feb 8, 2007 (gmt 0)

10+ Year Member



Hi there cameraman thanks for the warm welcome :)

u maked easy for me to understand how to make this work my current problem now is what code should i add in html so it post the variable assigned for $price

i added the variable code in the php form. thanks in advance!

coopster

10:02 pm on Feb 18, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



The POST variable index will be the value of the
name
attribute of the
<input>
element. See how cameraman used it in the code snippet? That's how you retrieve a POST form value.

jiji

10:56 pm on Mar 4, 2007 (gmt 0)

10+ Year Member



i redid the script and used sessions and all worked perfectly thanks alot really apreciate it!