Jump to content

Recommended Posts

Dear PHPFreaks,

 

I'm doing my dad a favour helping him out with a small website he's got. I can make simple html/css websites, but he'd like an orderform, one that works without any hasstle of opening outlook etc.

 

I came up with the following code, which seems to work fine, except for 2 things:

 

1) I'd like it to error when something isnt filled in properly on the current page (in red text) at the top of the form. If nessecary with refreshing the page, leaving fields filled with whatever people typed in it.

2) Redirecting the page (to any page i choose) when the form is filled in correctly.

 

This is the form I use:

<table border="0">

<tbody><tr>

<form action="bestellen.php" method="post">

      </tr><tr>
            <td align="right">Naam:</td>
            <td><input name="naam" size="25" type="text"></td>
      </tr>

      <tr>
            <td align="right">Achternaam:</td>
            <td><input name="achternaam" size="25" type="text"></td>
      </tr>

       <tr>
            <td align="right">Email:</td>
            <td><input name="email" size="25" type="text"></td>
      </tr>

      <tr>
            <td align="right">Straat & huisnummer:</td>
            <td><input name="straat" size="16" type="text"> <input name="huisnummer" size="4" type="text">
            </td></tr>


      <tr>
            <td align="right">Postcode:</td>
            <td><input name="postcode" size="7" type="text">

      </td></tr>

      <tr>
            <td align="right">Plaats:</td>
            <td><input name="plaats" size="25" type="text"></td>
      </tr>

           <tr>
            <td align="right">Telefoon:</td>
            <td><input name="telefoon" size="12" type="text"></td>
      </tr>

      <tr>
            <td align="right">Product:</td>
            <td><select name="product" size="4">
<option value="proefmonster">Proefmonster (Gratis!)</option>
<option value="1kartalin" selected="selected">1x Kartalin - €30,00</option>
<option value="2kartalin">2x Kartalin - €58,00</option>
<option value="3kartalin">3x Kartalin - €80,00</option>
</select></td>
      </tr>

            <tr><td align="right">Verzenden:</td>
            <td><select name="verzending" size="1">
<option value="proefmonster">N.v.t. bij proefmonster</option>
<option value="dhl" selected="selected">DHL (binnen 2 á 3 werkdagen) - €4,95</option>
<option value="tnt">TNT-Post (volgende werkdag) - €6,50</option>
</select></td>
      </tr>

    

      <tr>
            <td align="right">Opmerkingen:</td>
            <td><textarea name="opmerkingen" rows="5" cols="29"></textarea></td>
      </tr>
        <tr><td></td><td>
       <input name="verzenden" value="Verzenden" type="submit"> <input type="reset" value="Opnieuw">

 

And this is is the 'order.php' page it uses:

<?php

// your email address
$youremail = "myemail@myemail.com";

// field validation
if ($naam=="" || $achternaam=="" || $email=="" || $straat=="" || $huisnummer=="" || $postcode=="" || $plaats=="" || $telefoon=="")

{
print ("Alle velden moeten worden ingevuld!");
}

else {

// send email
$headers = "From: \"$naam\" <$email>\n";
$subject = "Bestelling Kartalin!"; 
$message = "$naam $achternaam \n$email \n\n\n$straat $huisnummer \n$postcode \n$plaats \n$telefoon \n\n\n$product \n$verzending \n\n\n\n$opmerkingen";

mail ("$youremail", "$subject", $message, $headers);
print ("Geachte $naam $achternaam, hartelijk dank voor uw bestelling. \nU krijgt binnen 24 uur uw factuur opgestuurd naar $email .");

} 
?>

 

As said, i'm not familiar with PHP, and not really interested in learning the insides.. hope you guys can help me out!

Link to comment
https://forums.phpfreaks.com/topic/215725-error-orderform-on-same-page/
Share on other sites

for the redirecting, use php's header() function and then exit(); when you want to redirect the user... in your case after the email script

header('Location: http://www.yourDomain.com');
exit();

 

if you want an error or success message, you can redirect to a success or error page or send the error/success in the url with $_GET ... or you could also send it via a session but I wouldn't for a public page.

And as for the $_GET error/success

 

And now for the form validation, you can use isset() to ensure that a variable is set

if (isset($_POST['email'])) {
echo "it is set";
}

// exclamation point reverses condition
if (!isset($_POST['email']))
{
echo "email is not set. Error";
}

 

that should get you started...

Your form is posting to a page called "bestellen.php". Is that the form page? If not, you want the form page to post to itself. You can do this by simplyleaving the action attribute blank. Then, just add logic at the top of the page to perform the validation. If validation fails, generate the error messages and redisplay the form. If validation passes include the processing page (order.php).

 

Here is a rewrite of the form page which will do the validation as well. I only included validation for the first three fields.

 

Note: I used an include to add the page to process the data after validation passes, using header() would remove all the data. But, using header after processing the data (for example taking the user to a thank you page) is a great idea. That way if a user refreshes the page it won't process the data a second time.

<?php
//Values for select lists
$productList = array(
    'proefmonster' => 'Proefmonster (Gratis!)',
    '1kartalin' => '1x Kartalin - €30,00',
    '2kartalin' => '2x Kartalin - €58,00',
    '3kartalin' => '3x Kartalin - €80,00'
    );

$verzendingList = array(
    'proefmonster' => 'N.v.t. bij proefmonster',
    'dhl' => 'DHL (binnen 2 á 3 werkdagen) - €4,95',
    'tnt' => 'TNT-Post (volgende werkdag) - €6,50'
    );

function createSelectOptions($optionList, $selectedValue=false)
{
    foreach($optionList as $value=>$text)
    {
        $selected = ($value===$selectedValue) ? ' selected="selected"' : '';
        echo "<option value=\"{$value}\"{$selected}>{$text}</option>\n";
    }
}

function is_email($email) 
{
    $formatTest = '/^[\w!#$%&\'*+\-\/=?^`{|}~]+(\.[\w!#$%&\'*+\-\/=?^`{|}~]+)*@[a-z\d]([a-z\d-]{0,62}[a-z\d])?(\.[a-z\d]([a-z\d-]{0,62}[a-z\d])?)*\.[a-z]{2,6}$/i';
    $lengthTest = '/^(.{1,64})@(.{4,255})$/';
    return (preg_match($formatTest, $email) && preg_match($lengthTest, $email));
}

//Create initial variables
$naam        = (isset($_POST['naam'])) ? trim($_POST['naam']) : '';
$achternaam  = (isset($_POST['achternaam'])) ? trim($_POST['achternaam']) : '';
$email       = (isset($_POST['email'])) ? trim($_POST['email']) : '';
$straat      = (isset($_POST['straat'])) ? trim($_POST['straat']) : '';
$huisnummer  = (isset($_POST['huisnummer'])) ? trim($_POST['huisnummer']) : '';
$postcode    = (isset($_POST['postcode'])) ? trim($_POST['postcode']) : '';
$plaats      = (isset($_POST['plaats'])) ? trim($_POST['plaats']) : '';
$telefoon    = (isset($_POST['telefoon'])) ? trim($_POST['telefoon']) : '';
$product     = (isset($_POST['product'])) ? trim($_POST['product']) : '';
$verzending  = (isset($_POST['verzending'])) ? trim($_POST['verzending']) : '';
$opmerkingen = (isset($_POST['opmerkingen'])) ? trim($_POST['opmerkingen']) : '';
$errorText = '';

if(isset($_POST))
{
    //User submitted data - perform validation
    $errors = array();

    if(empty($naam)) { $errors[] = "Name is required."; }
    if(empty($achternaam)) { $errors[] = "Achternaam is required."; }
    if(empty($email)) { $errors[] = "Email is required."; }
    else if(!is_email($email))  { $errors[] = "Email is not valid."; }

    if(count($errors)>0)
    {
        $errorText .= "<span style=\"color:#ff0000;\">";
        $errorText .= "The following errors occured:<ul>\n";
        foreach($errors as $errorMsg)
        {
            $errorText .= "<li>$errorMsg</li>";
        }
        $errorText .= "</ul><span style=\"color:#ff0000;\">";
    }
    else
    {
        //Form validation passed include page to process the data
        include('order.php');
        exit();
    }
}




?>
<html>
</head></head>
<body>
<?php echo $errorText; ?>
<form action="" method="post">
<table border="0">
      <tr>
            <td align="right">Naam:</td>
            <td><input name="naam" size="25" type="text" value="<?php echo $naam; ?>" /></td>
      </tr>
      <tr>
            <td align="right">Achternaam:</td>
            <td><input name="achternaam" size="25" type="text" value="<?php echo $achternaam; ?>" /></td>
      </tr>
       <tr>
            <td align="right">Email:</td>
            <td><input name="email" size="25" type="text" value="<?php echo $email; ?>" /></td>
      </tr>
      <tr>
            <td align="right">Straat & huisnummer:</td>
            <td>
                <input name="straat" size="16" type="text" value="<?php echo $straat; ?>" />
                <input name="huisnummer" size="4" type="text" value="<?php echo $huisnummer; ?>" />
            </td>
      </tr>
      <tr>
            <td align="right">Postcode:</td>
            <td><input name="postcode" size="7" type="text" value="<?php echo $postcode; ?>" /></td>
      </tr>
      <tr>
            <td align="right">Plaats:</td>
            <td><input name="plaats" size="25" type="text" value="<?php echo $plaats; ?>" /></td>
      </tr>
      <tr>
            <td align="right">Telefoon:</td>
            <td><input name="telefoon" size="12" type="text" value="<?php echo $telefoon; ?>" /></td>
      </tr>
      <tr>
            <td align="right">Product:</td>
            <td><select name="product" size="4">
                <?php createSelectOptions($productList, $product); ?>
                </select>
            </td>
      </tr>
      <tr>
            <td align="right">Verzenden:</td>
            <td><select name="verzending" size="1">
                <?php createSelectOptions($verzendingList, $verzending); ?>
                </select>
            </td>
      </tr>
      <tr>
            <td align="right">Opmerkingen:</td>
            <td><textarea name="opmerkingen" rows="5" cols="29" value="<?php echo $opmerkingen; ?>"></textarea></td>
      </tr>
      <tr>
            <td></td>
            <td><input name="verzenden" value="Verzenden" type="submit"> <input type="reset" value="Opnieuw"></td>
      </tr>
</table>
</form>

</body>
</html>

joel24, thanks for your help. Unfortunatly 90% of what you typ is a riddle to me. My PHP reading/writing skills suck  :shrug:

 

mjdamato thanks alot for taking the time to do that!

 

"bestellen.php" is Dutch for "order.php", it redirected to that page to check if all fields were checked, and if so, would send the form to designated email.

 

I've implemented it in the current website, and it looks like this (click). It appears to work, though everythings in red by default (even without touching the form at all), i'd like it to only turn red when people leave blanks in the form.

 

To add the fields it needs to check, I can add them below

//User submitted data - perform validation

right?

 

 

Thanks in advance,

your help is very appriciated!

Did you remove the condition to check if the form was submitted?

if(isset($_POST))
{
    //User submitted data - perform validation

 

That IF condition only performs validation if the user has submitted the form. So, the errors should not display on first accessing the page.

 

To add the fields it needs to check, I can add them below

//User submitted data - perform validation

right?

Yes, of course, hence the comment. I only added a few sample validations. You didn't provide any criteria on what or how you wanted validation to occur.

No I didnt remove any of the code, this is copied directly from the page you were looking at (from my previous post):

 

//Create initial variables
$naam        = (isset($_POST['naam'])) ? trim($_POST['naam']) : '';
$achternaam  = (isset($_POST['achternaam'])) ? trim($_POST['achternaam']) : '';
$email       = (isset($_POST['email'])) ? trim($_POST['email']) : '';
$straat      = (isset($_POST['straat'])) ? trim($_POST['straat']) : '';
$huisnummer  = (isset($_POST['huisnummer'])) ? trim($_POST['huisnummer']) : '';
$postcode    = (isset($_POST['postcode'])) ? trim($_POST['postcode']) : '';
$plaats      = (isset($_POST['plaats'])) ? trim($_POST['plaats']) : '';
$telefoon    = (isset($_POST['telefoon'])) ? trim($_POST['telefoon']) : '';
$product     = (isset($_POST['product'])) ? trim($_POST['product']) : '';
$verzending  = (isset($_POST['verzending'])) ? trim($_POST['verzending']) : '';
$opmerkingen = (isset($_POST['opmerkingen'])) ? trim($_POST['opmerkingen']) : '';
$errorText = '';

if(isset($_POST))
{

//User submitted data - perform validation

 

The criteria was pretty much wether the field was filled or not, so I reckon thats fine the way it is. Could perhaps do with stuff like the phone field, to only use numers and max 10 characters or something, but its not that important and it'll only complicate things  ;)

 

If I can get the error to load only when the form is filled/submitted, it should be pretty much complete!

 

Thanks for your quick reply and helpfullness!

In case anyone's still following this topic (thanks truckloads mjdamato):

 

This is how it looks now: http://daveoudshoorn.nl/bestellen.php

 

- When an error occurs, not just the UL with errors turn red, but all text below that command. Preferably only the UL can turn red, and (if not too complicated), the text of the field which contains the error may turn red.

 

- When an error occurs, the "comment" textarea (or 'opmerkingen' in Dutch) empties out. The rest of the fields remain with their info though (which is good). Is there a away to keep the text written in the comment area?

 

Code as it is now: bestellen.php

<?php
//Values for select lists
$productList = array(
    'Proefmonster (Gratis!)' => 'Gratis proefmonster',
    '1x 125gr. kartalin EUR 30,00' => '1x 125gr. kartalin €30,00',
    '2x 125gr. kartalin EUR 56,00' => '2x 125gr. kartalin €56,00',
    '3x 125gr. kartalin EUR 80,00' => '3x 125gr. kartalin €80,00'
    );

$verzendingList = array(
    'Gratis (alleen bij proefmonster)' => 'Gratis (alleen bij proefmonster)',
    'Via DHL (binnen 2 a 3 werkdagen) EUR 4,95' => 'Via DHL (binnen 2 á 3 werkdagen) €4,95',
    'Via TNT (volgende werkdag) EUR 6,50' => 'Via TNT (volgende werkdag) €6,50'
    );

function createSelectOptions($optionList, $selectedValue=false)
{
    foreach($optionList as $value=>$text)
    {
        $selected = ($value===$selectedValue) ? ' selected="selected"' : '';
        echo "<option value=\"{$value}\"{$selected}>{$text}</option>\n";
    }
}

function is_email($email) 
{
    $formatTest = '/^[\w!#$%&\'*+\-\/=?^`{|}~]+(\.[\w!#$%&\'*+\-\/=?^`{|}~]+)*@[a-z\d]([a-z\d-]{0,62}[a-z\d])?(\.[a-z\d]([a-z\d-]{0,62}[a-z\d])?)*\.[a-z]{2,6}$/i';
    $lengthTest = '/^(.{1,64})@(.{4,255})$/';
    return (preg_match($formatTest, $email) && preg_match($lengthTest, $email));
}

//Create initial variables
$naam        = (isset($_POST['naam'])) ? trim($_POST['naam']) : '';
$achternaam  = (isset($_POST['achternaam'])) ? trim($_POST['achternaam']) : '';
$email       = (isset($_POST['email'])) ? trim($_POST['email']) : '';
$straat      = (isset($_POST['straat'])) ? trim($_POST['straat']) : '';
$plaats      = (isset($_POST['plaats'])) ? trim($_POST['plaats']) : '';
$telefoon    = (isset($_POST['telefoon'])) ? trim($_POST['telefoon']) : '';
$product     = (isset($_POST['product'])) ? trim($_POST['product']) : '';
$verzending  = (isset($_POST['verzending'])) ? trim($_POST['verzending']) : '';
$opmerkingen = (isset($_POST['opmerkingen'])) ? trim($_POST['opmerkingen']) : '';
$errorText = '';

if(isset($_POST['naam']))
{
    //User submitted data - perform validation
    $errors = array();

    if(empty($naam)) { $errors[] = "Naam is verplicht."; }
    if(empty($achternaam)) { $errors[] = "Achternaam is verplicht."; }
    if(empty($email)) { $errors[] = "Email is verplicht."; }
    else if(!is_email($email))  { $errors[] = "Ongeldig emailadres."; }
    if(empty($straat)) { $errors[] = "Adres is verplicht."; }
    if(empty($plaats)) { $errors[] = "Postcode & woonplaats is verplicht."; }
    if(empty($telefoon)) { $errors[] = "Telefoonnummer is verplicht."; }
    if(empty($product)) { $errors[] = "Maak een productkeuze."; }
    if(empty($verzending)) { $errors[] = "Kies een verzendmethode."; }


    if(count($errors)>0)
    {
        $errorText .= "<span style=\"color:#ff0000;\">";
        $errorText .= "De volgende fout(en) zijn opgetreden:<ul>\n";
        foreach($errors as $errorMsg)
        {
            $errorText .= "<li>$errorMsg</li>";
        }
        $errorText .= "</ul><span style=\"color:#ff0000;\">";
    }
    else
    {
        //Form validation passed include page to process the data
        include('ordercomplete.php');
        exit();
    }
}

?>

 

And the form itself:

    <div id="form"><?php echo $errorText; ?>
<form action="" method="post">
<table border="0">
      <tr>
            <td align="right">Naam:</td>
            <td><input name="naam" size="25" type="text" value="<?php echo $naam; ?>" /></td>
      </tr>
      <tr>
            <td align="right">Achternaam:</td>
            <td><input name="achternaam" size="25" type="text" value="<?php echo $achternaam; ?>" /></td>
      </tr>
      <tr>
            <td align="right">Adres:</td>
            <td>
                <input name="straat" size="25" type="text" value="<?php echo $straat; ?>" />
            </td>
      </tr>
      <tr>
            <td align="right">Postcode & woonplaats:</td>
            <td><input name="plaats" size="25" type="text" value="<?php echo $plaats; ?>" /></td>
      </tr>
       <tr>
            <td align="right">Email:</td>
            <td><input name="email" size="25" type="text" value="<?php echo $email; ?>" /></td>
      </tr>
      <tr>
            <td align="right">Telefoon:</td>
            <td><input name="telefoon" size="12" type="text" value="<?php echo $telefoon; ?>" /></td>
      </tr>
      <tr>
            <td align="right">Ik bestel:</td>
            <td><select name="product" size="4">
                <?php createSelectOptions($productList, $product); ?>
                </select>
            </td>
      </tr>
      <tr>
            <td align="right">Verzendwijze:</td>
            <td><select name="verzending" size="3">
                <?php createSelectOptions($verzendingList, $verzending); ?>
                </select>
            </td>
      </tr>
      <tr>
            <td align="right">Opmerkingen:</td>
            <td><textarea name="opmerkingen" rows="5" cols="29" value="<?php echo $opmerkingen; ?>"></textarea></td>
      </tr>
      <tr>
            <td></td>
            <td><input name="verzenden" value="Verzenden" type="submit"> <input type="reset" value="Opnieuw"></td>
      </tr>
</table>
</form>
</div>

 

Confirmpage (when you submitted your form)

<?php

// your email address
$youremail = "myemail@gmail.com, $email";

// field validation
if ($naam=="" || $achternaam=="")

{
print ("Alle velden moeten worden ingevuld!");
}

else {

// send email
$headers = "From: \"$naam\" <$email>\n";
$subject = "Bestelling Kartalin";
$from    = "Kartalin.nl";
$message = "<strong>Let op! Dit is een orderbevestiging, de factuur volgt binnen 24 uur.</strong><br /></br /><br /></br />
<hr />

Beste $naam $achternaam,<br /></br /><br /></br />

Hartelijk dank voor je bestelling bij <strong>Kartalin.nl</strong><br /></br /><br /></br />


Wij hebben onderstaande gegevens van je binnengekregen:<br />

<strong>$naam $achternaam</strong><br />
<strong>$straat</strong><br />
<strong>$plaats</strong><br />
<strong>$telefoon</strong><br />
<strong>$email</strong><br /><br />

Je bestelling: <strong>$product</strong><br />
Verzendwijze: <strong>$verzending</strong><br />
Opmerking: <strong>$opmerkingen</strong><br /><br /><br />


Je ontvangt van bovenstaande bestelling z.s.m een factuur; Zodra je betaling bij ons binnen is wordt je bestelling nog dezelfde dag naar je verstuurd";

mail ("$youremail", $subject, $message, "From: $from\nContent-Type: text/html; charset=iso-8859-1");

} 
?>

you're not closing the <span> tag which sets the text to #FF0000


    if(count($errors)>0)
    {
        $errorText .= "<span style=\"color:#ff0000;\">";
        $errorText .= "De volgende fout(en) zijn opgetreden:<ul>\n";
        foreach($errors as $errorMsg)
        {
            $errorText .= "<li>$errorMsg</li>";
        }
        $errorText .= "</ul></span>" //was span style=\"color:#ff0000;\";
    }

- When an error occurs, the "comment" textarea (or 'opmerkingen' in Dutch) empties out. The rest of the fields remain with their info though (which is good). Is there a away to keep the text written in the comment area?

 

Ok, I made the mistake in the code I posted to you, but you still should have caught the problem. As my signature states, I don't typically test the code I provide and I usually just write the code "on-the-fly".  Anyway, textareas don't have a value parameter:

 

<textarea name="opmerkingen" rows="5" cols="29" value="<?php echo $opmerkingen; ?>"></textarea>

 

The value goes between the tags:

<textarea name="opmerkingen" rows="5" cols="29"><?php echo $opmerkingen; ?></textarea>

 

Note: you will need to "clean" the inputs (all of them) to protect against values that may screw up the rendered page. For example, if the user entered '<' or ", etc.

 

As my signature states, I don't typically test the code I provide and I usually just write the code "on-the-fly". 

Thats OK. It'd take me weeks to write something like that. I'm having a hard time even reading PHP ;)

 

Note: you will need to "clean" the inputs (all of them) to protect against values that may screw up the rendered page. For example, if the user entered '<' or ", etc.

 

I noticed that now. The form blocks whenever a special character is entered in any of the fields. Is that hard to fix?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.