Calculate delivery charge based on select option

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Lee_E31
Forum Newbie
Posts: 4
Joined: Mon Nov 16, 2009 2:18 pm

Calculate delivery charge based on select option

Post by Lee_E31 »

Hi all, new to php so bear with me!

I am setting up a small online shop using php and mysql but getting stuck on calculating a delivery charge.
Basically when a customer is checking out they select a delivery option from a drop down select list, here is the code i'm using:

Delivery options:
<select name="shipping">
{section name=i loop=$obj->mShippingInfo}
<option value="{$obj->mShippingInfo.shipping_id}">
{$obj->mShippingInfo.shipping_type}
</option>
{/section}

what i'd like to do now is to assign a cost variable based on which selection the customer makes, maybe onChange or other, (cost amount is stored in the table as shipping_cost), then update a total amount before they commit the order.

Can any help? any examples or tutorials would really be appreciated.

Thanks,
Lee
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Calculate delivery charge based on select option

Post by iankent »

Do you mean you want the page to dynamically update as soon as the user chooses an option from the list? I.e., without going back to the server for an update? If so, this is a javascript rather than PHP question.

In that case, you do need to use an onchange event on the select tag, and it'll need to call a javascript function that updates the shipping cost.

For arguments sake lets say your form looks like this:

Code: Select all

<select name="shipping" id="shipping" onchange="updateTotal();">
<option value="collect" selected="selected">I'll collect it (free)</option>
<option value="abc">ABC Shipping Ltd (24 hour)</option>
<option value="def">DEF Couriers (3 working days)</option>
</select>
Your order will cost: $<span id="ordercost">24.00</span>
Your delivery will cost: $<span id="delivery">0.00</span>
Your order + delivery costs: $<span id="total">24.00</span>
Your javascript could would then need to look something like this:

Code: Select all

<script>
var shipping = Array();
shipping['collect'] = 0.00;
shipping['abc'] = 14.99;
shipping['def'] = 8.99;
 
function updateTotal() {
    var ordercost = parseFloat(document.getElementById('ordercost').innerText);
    var e_totalcost = document.getElementById('total');
    var e_delivery = document.getElementById('delivery');
    var shipping_cost = shipping[document.getElementById('shipping').value];
    e_totalcost.innerText = shipping_cost + ordercost;
    e_delivery.innerText = shipping_cost;
}
</script>
Your array of shipping costs (just inside the script tag) will need to be output by php using data from your table. When the user chooses a new value, updateTotal gets the current order cost, gets the element for the total cost, gets the shipping cost based on the current selection, adds the order and shipping cost together and puts the result in the total cost html element.

Hope that makes sense :P And apologies if the code isn't spot on - typed directly from what little memory I have :)
Lee_E31
Forum Newbie
Posts: 4
Joined: Mon Nov 16, 2009 2:18 pm

Re: Calculate delivery charge based on select option

Post by Lee_E31 »

thanks for the quick response.

i'd had a similar thought and if i hard code the amounts it adds up and displays ok. I don't mind if it uses javascript and onchange or goes back to the server or updates, just would like to see it working dynamically, but having some difficulty bringing those values in from the db table based on the users selection.

Any thoughts?
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Calculate delivery charge based on select option

Post by iankent »

You need to use PHP to output part of the script tag, e.g.

Code: Select all

<?
$q = "select id,cost from shipping_cost";
$r = mysql_query($q);
?>
<script>
var shipping = Array();
<?
while($line = mysql_fetch_assoc($r)) {
    ?>
    shipping[<?=$line['id']?>] = <?=$line['cost']?>;
    <?
}
?>
function updateTotal() {
    var ordercost = parseFloat(document.getElementById('ordercost').innerText);
    var e_totalcost = document.getElementById('total');
    var e_delivery = document.getElementById('delivery');
    var shipping_cost = shipping[document.getElementById('shipping').value];
    e_totalcost.innerText = shipping_cost + ordercost;
    e_delivery.innerText = shipping_cost;
}
</script>
This will generate the javascript array on-the-fly using the shipping costs from your database. You'll also need to update the form code to use a similar query, e.g.:

Code: Select all

 
<select name="shipping" id="shipping" onchange="updateTotal();">
<?
$q = "select id,title from shipping_cost;";
$r = mysql_query($q);
while($line = mysql_fetch_assoc($r)) {
?>
<option value="<?=$line['id']?>" <? if($line['id']=="collect") { ?>selected="selected"<? } ?>><?=$line['title']?></option>
<? } ?>
</select>
Your order will cost: $<span id="ordercost">24.00</span>
Your delivery will cost: $<span id="delivery">0.00</span>
Your order + delivery costs: $<span id="total">24.00</span>
 
That bit will output the correct <option> tags from the table using the same ID as the javascript ones do, but displaying the title instead of the cost. Update the queries to match your db :) update the bit where it says $line['id'] == "collect" to the ID of whichever you want the default shipping to be - that way your recommended shipping is selected from the start. If your default shipping costs more than 0.00, you'll need to output the correct value in the delivery <span> and update the total value in the total <span>

hth
Lee_E31
Forum Newbie
Posts: 4
Joined: Mon Nov 16, 2009 2:18 pm

Re: Calculate delivery charge based on select option

Post by Lee_E31 »

great, will give that a try. thanks :)
Lee_E31
Forum Newbie
Posts: 4
Joined: Mon Nov 16, 2009 2:18 pm

Re: Calculate delivery charge based on select option

Post by Lee_E31 »

still having some issues with the dynamic update, could you take a look and point us in the right direction?

sample table:

Code: Select all

mysql> select * from shipping;
+-------------+-------------------+---------------+--------------------+
| shipping_id | shipping_type     | shipping_cost | shipping_region_id |
+-------------+-------------------+---------------+--------------------+
|           1 | Next Day          |         20.00 |                  2 |
|           2 | Standard          |         10.00 |                  2 |
|           3 | Special           |          5.00 |                  2 |
|           4 | Free              |          0.00 |                  2 |
+-------------+-------------------+---------------+--------------------+
4 rows in set (0.02 sec)

here is the code i have so far:

Code: Select all

<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pwd = 'password';
$totalcost = 0;
$ordercost = 10;
$e_delivery = 0;
$shipping_cost = 0;
$e_totalcost = $ordercost +$e_delivery;
 
$database = 'mydb';
$table = 'shipping';
 
if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");
 
if (!mysql_select_db($database))
    die("Can't select database");
 
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
    die("Query to show fields from table failed");
}
 
$fields_num = mysql_num_fields($result);
 
echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
 
for($i=0; $i<$fields_num; $i++)
{
    $field = mysql_fetch_field($result);
    echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
 
while($row = mysql_fetch_row($result))
{
    echo "<tr>";
 
    foreach($row as $cell)
        echo "<td>$cell</td>";
 
    echo "</tr>\n";
}
mysql_free_result($result);
 
echo "<p>";
 
echo "Your order total is: " . $ordercost;
echo "<br>";
echo "Delivery Costs: " . $shipping_cost;
echo "<br>";
echo "Total Due: " . $e_totalcost;
echo "</p>";
?>
<html>
<head>
<script>
<!--
var shipping = Array ();
<?
$sql = "SELECT shipping_id, shipping_cost FROM shipping";
$r = mysql_query($sql);
while($line = mysql_fetch_assoc($r)) {
    ?>
    shipping[<?=$line['shipping_id']?>] = <?=$line['shipping_cost']?>;
    <?
}
?>
 
function updatetotal() {
    var ordercost = parseFloat(document.getElementById('ordercost').innerText);
    var e_totalcost = document.getElementById('total');
    var e_delivery = document.getElementById('delivery');
    var shipping_cost = shipping[document.getElementById('shipping').value];
    e_totalcost.innerText = shipping_cost + ordercost;
    e_delivery.innerText = shipping_cost;
}
-->
</script>
<title>Populate Select List from db table</title>
</head>
 
<body>
<select name="delivery" id="delivery" onchange="updatetotal();">
<?php
$sql = "SELECT shipping_id, shipping_type FROM shipping";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs))
{
  echo "<option value=\"".$row['shipping_id']."\">".$row['shipping_type']."\n  ";
 
}
?>
</select>
</body>
</html>
thanks in advance.
User avatar
iankent
Forum Contributor
Posts: 333
Joined: Mon Nov 16, 2009 4:23 pm
Location: Wales, United Kingdom

Re: Calculate delivery charge based on select option

Post by iankent »

See my first reply to your question. You haven't put <span>s around the values when you output them in this bit:

Code: Select all

 
echo "<p>";
 
echo "Your order total is: " . $ordercost;
echo "<br>";
echo "Delivery Costs: " . $shipping_cost;
echo "<br>";
echo "Total Due: " . $e_totalcost;
echo "</p>";
 
Post Reply