Page 1 of 1

Having trouble with Functions

Posted: Tue Oct 18, 2011 1:25 pm
by jetlife76
Trying to get my program to calculate shipping on an item and i need to have my calculations in a function.
Here's what i have, everything prints out except the shipping,

Code: Select all

<?php
// Input Data From Form
$Cost = $_POST['fielda'];
//Calculate tax 
$Tax = ($Cost * .06);

$Ship = 0;

//Set Current Date & Shipping Date (15 days)
$Date = date('l, F d, Y');
$ShipDate = date('F d, Y',strtotime('+ 15 days'));

//Calculate Shipping
function shipping_cost($Cost) {

if ($Cost > 0 && $Cost <= 25.00 ){
	$Ship = 3.00; }
if ($Cost >= 25.01 && $Cost <= 50.00 ){
	$Ship = 4.00;}
if ($Cost >= 50.01 && $Cost <= 75.00) {
	$Ship = 5.00;}
if ($Cost > 75.00) {
	$Ship = 6.00;}
	
return $Ship; }
	
	//Calculate Order Total
$Total = ($Cost + $Tax + $Ship);


$Cost2 = number_format($Cost,2);
$Tax2 = number_format($Tax,2);
$Ship2 = number_format($Ship,2);
$Total2 = number_format($Total,2);


    print "Date: $Date<br><br>";
    print "Cost: $$Cost2<br><br>";
     print "Tax: $$Tax2<br><br>";
print "Ship: $$Ship2<br><br>";
   print "Total: $$Total2<br><br>";
print "Estimated Ship Date is $ShipDate<br> " ;
?>

Re: Having trouble with Functions

Posted: Tue Oct 18, 2011 1:30 pm
by ouchiko
Er, you don't call shipping_cost anywhere...

$ship=shipping_cost($cost);

Re: Having trouble with Functions

Posted: Tue Oct 18, 2011 2:02 pm
by jetlife76
I dont think that's the issue, i got a bunch of errors for lines 19 , 24 and others for undefined variables and number format

Re: Having trouble with Functions

Posted: Tue Oct 18, 2011 2:52 pm
by jetlife76
Ok must've made made error somewhere but it's still not giving me a shipping cost, its giving me zero for shipping

Re: Having trouble with Functions

Posted: Tue Oct 18, 2011 2:55 pm
by twinedev
Well is the the exact code you have? Is this line 19?
[c] $Ship = 4.00;}[/c]
In the code you gave, line 24 is a blank line...

You are still going to have the issue that in the code you presented, as mentioned, nothing is calling the function to calculate the shipping costs.

Also, to save on some coding, for the calculating of costs, you could do the following:

Code: Select all

		if ($Cost <= 25.00) {
			$Ship = 3.00;
		}
		elseif ($Cost <= 50.00) {
			$Ship = 4.00;
		}
		elseif ($Cost <= 75.00) {
			$Ship = 5.00;
		}
		else {
			$Ship = 6.00;
		}
If not only reduces logic in the code, makes it so if you change the limits (say you want to do it every $30 instead of $25, only one place to change the limits, don't have to change 25.00 to 30.00 and then on next block also change 25.01 to 30.01 (or worse, forget to change it, then you are getting higher shipping rates for $27 than you expect)

-Greg

Re: Having trouble with Functions

Posted: Tue Oct 18, 2011 3:16 pm
by jetlife76
Thanks Greg i got it to work i had commented out where i called it, typing too fast, lol