Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Form Validation

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #44869
    LaurelBrittany
    Participant

    I am trying to validate a form and I keep getting an error: Notice: Undefined variable: errorString in C:xampphtdocsintroducingphpemailrequired_fieldsindex.php on line 7

    The form fields also fill with error text. The form works fine

    <html>
    <head>
    <title>PHP Form Processing Example</title>
    </head>
    <body>

    <?php echo $errorString; ?>

    <form action="process.php" method="POST">
    Name:*<br /><input type="text" name="Name" value="<?php echo $Name; ?>" /><br /><br />
    Email:*<br /><input type="text" name="Email" value="<?php echo $Email; ?>" /><br /><br />
    URL:*<br /><input type="text" name="URL" value="<?php echo $URL; ?>" /><br /><br />
    Company:<br /><input type="text" name="Company" value="<?php echo $Company; ?>" /><br /><br />
    <input type="submit" name="submit" value="Submit Form" />
    </form>

    </body>
    </html>
    Check out this Pen!

    This is the process.php

    <?php
    /*
    * Specify the field names that are in the form. This is meant
    * for security so that someone can't send whatever they want
    * to the form.
    */
    $allowedFields = array(
    'Name',
    'Email',
    'URL',
    'Company',
    );

    // Specify the field names that you want to require...
    $requiredFields = array(
    'Name',
    'Email',
    'URL',
    );

    $errors = array();
    foreach($_POST AS $key => $value)
    {
    // first need to make sure this is an allowed field
    if(in_array($key, $allowedFields))
    {
    $$key = $value;

    // is this a required field?
    if(in_array($key, $requiredFields) && $value == '')
    {
    $errors[] = "The field $key is required.";
    }
    }
    }

    // were there any errors?
    if(count($errors) > 0)
    {
    $errorString = '<p>There was an error processing the form.</p>';
    $errorString .= '<ul>';
    foreach($errors as $error)
    {
    $errorString .= "<li>$error</li>";
    }
    $errorString .= '</ul>';

    // display the previous form
    include 'index.php';
    }
    else
    {
    // At this point you can send out an email or do whatever you want
    // with the data...

    // each allowed form field name is now a php variable that you can access

    // display the thank you page
    header("Location: thanks.html");
    }

    Check out this Pen!

    #135569
    unasAquila
    Participant

    you need to check if the variable is initialize i.e

    if(!isset $errorString){
    //stuff to do if $errorString is not set
    }else{
    echo $errorString;
    }

    As for the form fields add something like

    !empty($Name) ? echo $Name : echo ”;

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘Back End’ is closed to new topics and replies.