NEWBIE - how to pass options

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
User avatar
splitdecision
Forum Newbie
Posts: 5
Joined: Wed May 23, 2007 6:03 pm

NEWBIE - how to pass options

Post by splitdecision »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


I am new at PHP and need help with the following PayPal form. I am trying to pass shipping information to PayPal based on the users selection in the form. There are three choices with two results; 1. PDF 2. Mail 3. Gift Box - and the results would be, for choice one and two shipping would be $0 and for the Gift Box shipping would be $10. 

Here is the form:

[syntax="html"]<form action="{path={city}_Spa_Where_You_Are/Confirm_Your_Purchase}" method="post" enctype="multipart/form-data">
<fieldset>
	<legend class="h3">Fill out the Gift Gift Certificate</legend>

	<div class="form_item"><label for="recipient">This Entitles:</label>
        <input type="hidden" name="submitted" value="yes" />
        <input type="text" name="recipient" id="recipient" maxlength="200" />
        </div>
	<div class="caption">Insert name of recipient as you want it to appear on the gift certificate.</div>

	<div class="form_item"><label for="amount">To Amount (in US Dollars):</label>
        <input type="text" name="amount" id="amount" />
        </div>
	<div class="caption">You may give any amount from $50-$1000. Your gift may be applied toward spa services, parking expenses and gratuities.</div>
 
	<div class="form_item"><label for="sender">A Gift From:</label>
        <input type="text" name="sender" id="sender" maxlength="100" />
        </div>
	<div class="caption">Insert the name of the giver(s) as you want it to appear on the certificate.</div>




<fieldset>
	<legend class="h3">Shipping Options</legend>
                         <input type="hidden" name="shipping_amount" id="shipping_amount" />
        <div class="form_item"><div class="label">How would you like you gift certificate delivered?</div><div class="input">
                        <select name="shipping">
                        <option value="nogo">Make a selection...</option>
                        <option value="PDF">Receive a PDF</option>
                        <option value="Mail">Mail it (No charge)</option>
                        <option value="Gift Box">Ship in a gift Box with Bow ($10.00 charge)</option>
                        </select>
and here is the PHP handler:[/syntax]

Code: Select all

<?php
			//Default to showing the form.
			$goodtogo = false;
			
			//Handle the incoming data.
			if ($_POST['submitted'] == "yes"){
				//Let's declare a submission value that tells us if we are fine.
				$goodtogo = true;

				//Validate the recipient.
				try {
					if (trim ($_POST['recipient']) == ""){
						$goodtogo = false;
						throw new exception ("Sorry, you must enter a recipient.<br />");
					}
				} catch (exception $e) {
					?><span class="alert"><?php echo $e->getmessage(); ?></span><?php
				}
				//Validate the amount.
				try {
					if (trim ($_POST['amount']) == ""){
						$goodtogo = false;
						throw new exception ("Sorry, you must enter a amount.<br />");
					}
				} catch (exception $e) {
					?><span class="alert"><?php echo $e->getmessage(); ?></span><?php
				}
                               //Validate the sender.
				try {
					if (trim ($_POST['sender']) == ""){
						$goodtogo = false;
						throw new exception ("Sorry, you must enter a name.<br />");
					}
				} catch (exception $e) {
					?><span class="alert"><?php echo $e->getmessage(); ?></span><?php
				}
				//Validate the select box.
				try {
					if ($_POST['shipping'] == "nogo"){
						$goodtogo = false;
						throw new exception ("Please make a selection.<br />");
					}
				} catch (exception $e) {
					?><span class="error"><?php echo $e->getmessage(); ?></span><?php
				}


                                // calculate shipping
                                function add_shipping () {
                                global $shipping_chargeVars;
                                $shipping_method = $_POST ['shipping'];
                                $ten = 10;
                                $free = 0;
                                $shipping_charge = ($shipping_method == "Gift_box");
                                echo $shipping_charge;
                               }                                                                      
				

				
				//Now, if there were no errors, we can output the results.
				if ($goodtogo){
                                    
					echo "To: " . $_POST['recipient'] . "<br />";
					echo "From: " . $_POST['sender'] . "<br />";
					echo "Amount: " . $_POST['amount'] . "<br />";
                                        echo "Shipping: " . $_POST['shipping'] . "<br />";
                                       
					?>
The questionable area is under calculate "shipping"


I am not sure if using a function is the right way to go or try and use a IF/ELSE statement? I need to have the selected option posted for the user to see what they selected and another variable posted to put in the paypal form.

Any help would be appreciated, like I said I am new and sorry if my question is not clear.

Split.


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Post by califdon »

You need to learn how functions are used. You defined the function add_shipping(), but you never called it in your script! A function doesn't do anything until you call it. I don't think your function will work, in any case; it makes no sense to me. I suggest you start with reading http://us.php.net/tut.php.
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Why are you using exceptions for simple validation error handling? In your case, the simplest thing to do would be something like:

Code: Select all

<?php
// calculate shipping
$shipping_charge = 0;
if (isset($_POST['shipping']))
{
    if ($_POST['shipping'] == 'box')
    {
        $shipping_charge = 10;
    }
}
?>
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

You also only really need one try/catch block unless your trying to display multiple error messages. Using exceptions in form processors is a good habit to get into though. Did you write all that code yourself?
smudge
Forum Contributor
Posts: 151
Joined: Sun May 20, 2007 12:13 pm

Post by smudge »

try something like this:

Code: Select all

#define vars
$errors=array();
$recip=trim($_POST['recipient']);
$amt=trim($_POST['amount']);
$sender=trim($_POST['sender']);
$shipping_post=trim($_POST['shipping']);

if($_POST['submitted']){
  #check errors
  if(!$recip || $recip==""){
    array_push($errors,"Sorry, you must enter a recipient.");
  }
  if(!$amt || $amt==""){
    array_push($errors,"Sorry, you must enter an amount.");
  }
  if(!$sender || $sender==""){
    array_push($errors,"Sorry, you must enter a name.");
  }
  if(!$shipping_post || $shipping_post=="nogo"){
    array_push($errors,"Please make a selection.");
  }
} else {
  array_push($errors,"The form has not been submitted.");
}

#now that errors are out of the way...

if(sizeof($errors)>0){#if we have errors
  foreach($errors as $e){
    echo "<span class='alert'>$e</span><br />";
  }
} else {#if we don't
  #calculate shipping cost
  $ship_cost=0;
  if($shipping_post == "Gift_box"){
    $ship_cost=10;
  }
  echo "To: $recip <br />";
  echo "From: $sender <br />";
  echo "Amount: $amt <br />";
  echo "Shipping: \${$ship_cost} <br />";
}
That should do it. I tried to use some different facets of PHP programming to help out a learning php coder. If it produces errors, try to debug it yourself. :wink: It's how I learned PHP

edit 7:12pm: I just noticed, and am curious as to how your form action works. That is, if that's not just a sample address.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

Sorry I was bored. I would have written the whole damn thing and tested it but I'm on a laptop.

Code: Select all

// valid shipping options..
$shipping_options = array('Gift Box', 'Blah', 'Blah');


function post($key)
{
    return (isset($_POST[$key])) ? trim($_POST[$key]) : null;
}

$errors= array();

if (post('submitted') !== null)
{
    // process post variables..
    $recipient = post('recipient');
    $amount    = post('amount');
    $sender    = post('sender');
    $shipping  = post('shipping');

    // validate recipient
    if (strlen($recipient) < 2) { $errors[] = "Sorry, you must enter a recipient."; }
    
    // validate amount as int or decimal..
    if (!preg_match('#^\d{1,12}|\d{1,12}\.{1}\d{2}$#', $amount)) { $errors[] = "Sorry, you must enter an amount."; }
    
    // validate sender..
    if (strlen($sender) < 2) { $errors[] = "Sorry, you must enter a name."; }
    
    // validate shipping..
    if (($shipping == "nogo") || (!in_array($shipping, $shipping_options))) { $errors[] = "Please make a selection."; }
    
    if (count($errors) > 0)
    {
        echo "<span class='alert'>" . implode("</span><br /><span class='alert'>", $errors) . "</span><br />";
    } else {
        $ship_cost = 0;
        $ship_cost = ($shipping == "Gift_box") ? 10 : $ship_cost;
        
        echo "To: $recip <br />";
        echo "From: $sender <br />";
        echo "Amount: $amt <br />";
        echo "Shipping: \${$ship_cost} <br />";
    }
}
smudge
Forum Contributor
Posts: 151
Joined: Sun May 20, 2007 12:13 pm

Post by smudge »

Ok, ok, you win astions. :lol: Split, his code is so much better than mine, and uses less repetitiveness (see sig), and although they both have the same output, his has better error checking and a more efficient way to run through errors.

I had forgotten that you could use $arr[] instead of array_push, but I prefer to stay away from regx, no matter how useful it is. And what exactly is the difference b/t count and sizeof when using an array?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

sizeof is an alias of count, so they are the same.
User avatar
splitdecision
Forum Newbie
Posts: 5
Joined: Wed May 23, 2007 6:03 pm

Post by splitdecision »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


WOW guys, thanks for all of the help and quick responses.

Everah, what you posted is what I was trying to do but I didn't know you could use the variable in the ELSE statement like that - Thanks.

astions - Thanks for your suggestions, I looked at the code you wrote and it makes a lot of sense. The try/catch bloke snippet came from a book I'm using to learn PHP ( PHP 5 recipes ) Yours seems a lot easier to write and read. I have to look up the $key expression, I'm not sure how that works in your code, but thanks for all the help ( you to smudge )

My next task is to figure out how to limit the amount input to error if it's under $50.00, I think I have an idea but I'm not sure how to handle money like that. If the user enters 5.00 for $5 or 50 for $50.00 I would like to always have the output have the same format - $100.00. I have seen something like this but I'm not sure how it works

Code: Select all

ereg("(\\$)?([0-9]+)(\\.[0-9]{2})?",$_POST['amount'], $amount_parts);
  $clean_amount = $amount_parts[2];
  if ($amount_parts[3] != "") $clean_amount .= $amount_parts[3];
  else $clean_amount .= ".00";
  $total_amount = (float)$clean_amount+(float)$ship_amount[1];
Back to work

Thanks again for all your help


feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
splitdecision
Forum Newbie
Posts: 5
Joined: Wed May 23, 2007 6:03 pm

Post by splitdecision »

So Astions, in your code

Code: Select all

if (!preg_match('#^\d{1,12}|\d{1,12}\.{1}\d{2}$#', $amount)) { $errors[] = "Sorry, you must enter an amount."; }
I am trying understand the number checking, what confuses me is the use of "12" d{1,12} my first thought would be it should be 9 like 1-9 or 0-9. Where can I read about what you have there?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

It's checking for a digit which is 1 to 12 characters long. You will probably just want to remove any $ from that variable before error checking since you may be using it in mathematical calculations anyway. $key is just a variable that holds the array index to check. It's nothing special and could be called anything. Once you have removed the $ sign you can just add a condition that will verify the value of shipping is < 50. Since a - will not pass the regex test, you won't have to worry about it being a negative number.
User avatar
splitdecision
Forum Newbie
Posts: 5
Joined: Wed May 23, 2007 6:03 pm

Post by splitdecision »

OK, that makes a lot of sense. Hmmm 12 digits long, that would be nice!

At the end of the error handling you used this

Code: Select all

.{1}\d{2}$#'
I am assuming that would mean that the decimal could be one or two digits like $50.3 or $50.30 and the $ means it won't reject it if the user adds a dollar sign. So my next task is to strip the dollar sign from the variable (if it's there) and check if it is larger then 50 then add the shipping if it applies for a total amount.

Thanks for your help astions.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

The \.{1} means it can contain up to 1 decimal point. The ^ means beginning of string, and the $ means end of string. Data with a $ in it would fail the test. Any dollar signs need to be removed before you test against that regex.

All together the expression reads:

a number 0-9 repeating from 1 to 12 times OR a number 0-9 repeating 1 to 12 times followed by 1 decimal point followed by 2 digits.
User avatar
splitdecision
Forum Newbie
Posts: 5
Joined: Wed May 23, 2007 6:03 pm

Post by splitdecision »

Thanks for your patients astions, I really appreciate it. I'll tinker around with the info you gave me and see what I can do. By the way I tested the script you provided and everything worked as advertised.

I am sure I'll have plenty more questions
Post Reply