Field Validation Question

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

Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Field Validation Question

Post by Pavilion »

Your requested changes have been made.

I entered valid and invalid data.

The code sent me back to register2.html, no error messages for invalid data and no insertion of valid data.

Celauran - thank you so much for helping me work through this. Just the process of working with the script and learning what the script is doing is giving me a fuller understanding of both process and syntax.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Field Validation Question

Post by Celauran »

What sent you back to register2? I don't see any redirects in the code you posted earlier.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Field Validation Question

Post by Pavilion »

Celauran wrote:What sent you back to register2? I don't see any redirects in the code you posted earlier.
That is one of the things really confusing me. I copied and pasted your code - nothing more. Right now I am sitting here looking at the register_post2.php and do not see any redirects either. Here is the register_post2.php again:

Code: Select all

<?php
// include database connection file, if connection doesn't work the include file will throw an error message
include '../schedule/db_files/db_connect.php';

$errors = array();
if (!empty($_POST))
{
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    if (!$email)
    {
        $errors['email'] = "Not a valid email address.";
    }
    else
    {
        $email = mysql_real_escape_string($_POST['email']);
        $query = "SELECT COUNT(EmailAddress) FROM ContactTbl WHERE EmailAddress = '{$email}'";
        list($email_count) = mysql_fetch_row(mysql_query($query));

        if ($email_count)
        {
            $errors['email'] = "That email address is already in use.";
        }
    }

    if (!$_POST['fname'])
    {
        $errors['fname'] = "First name cannot be empty.";
    }
    if (!$_POST['lname'])
    {
        $errors['lname'] = "Last name cannot be empty.";
    }
}

if (!empty($_POST) && empty($errors))
{
    $fname = mysql_real_escape_string(trim($_POST['fname']));
    $lname = mysql_real_escape_string(trim($_POST['lname']));

	$query = "INSERT INTO ContactTbl (FName, LName, EmailAddress) VALUES ('{$fname}', '{$lname}', '{$email}')";
    mysql_query($query) or die(mysql_error());
}
?>
Could there be something going on with the html file, where register_post2.php isn't even allowed to execute. At the end of the day, I am landing on register2.html with no information in any of the fields.

Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Field Validation Question

Post by Celauran »

I just checked your code for register2; there's nothing in the form action. It's never hitting the PHP page.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Field Validation Question

Post by Pavilion »

Celauran - hold up. I found an error in my html file. Let me do some testing and I'll get back to you. A client is suppose to call within minutes, so I may not be able to test until after work with this client is completed. But... I will get back to you with results.

Thanks again - Pavilion
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Field Validation Question

Post by Pavilion »

Celauran:

The results are in - still waiting on a client call - but I'll just post this while I wait.
  • Valid entries (valid fname, lname, email addresses) are being inserted into the table. THANK YOU!
  • Empty fname fields return an blank white screen - no error message.
    Empty or invalid email addresses return a blank white screen - no error message
Thanks again for your patience and help. Gotta go... but will check in on this later.

Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Field Validation Question

Post by Celauran »

That's expected behaviour from splitting the script in two. Add the error messages to session data and use a header redirect back to the form.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Field Validation Question

Post by califdon »

Your register2.html file has some PHP code in it. Unless your web server is configured to allow it (normally it will not be), this just won't work, because the standard server configuration requires that a file that is to be preprocessed must have a file extension of .php. Try changing the filename to register2.php and see what happens.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Field Validation Question

Post by Pavilion »

Celauran wrote:That's expected behaviour from splitting the script in two. Add the error messages to session data and use a header redirect back to the form.
OK - I'm completely stumped. Celauran - since I'm at a "baby steps" level in all of this, I decided to first learn about "session data" and save the redirect for later. Following are my two scripts. Both are now php files.

register.php

Code: Select all

<?php
session_start();
// store post data as session data
$_SESSION=array_merge($_SESSION,$_POST);
?>

<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
        <title>Contact Form</title>
        <style type="text/css">
            span.error
            {
                color: #F00;
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <form action="register_post2.php" method="post">
            <label for="fname">First Name</label>
            <input type="text" name="fname" />
            <?php if (isset($errors['fname'])): ?>
            <span class="error"><?php echo $errors['fname']; ?></span>
            <?php endif; ?><br />

            <label for="lname">Last Name</label>
            <input type="text" name="lname" />
            <?php if (isset($errors['lname'])): ?>
            <span class="error"><?php echo $errors['lname']; ?></span>
            <?php endif; ?><br />

            <label for="email">Email Address</label>
            <input type="text" name="email" />
            <?php if (isset($errors['email'])): ?>
            <span class="error"><?php echo $errors['email']; ?></span>
            <?php endif; ?><br />

            <input type="submit" value="Submit" />
        </form>
    </body>
</html>
register_post2.php

Code: Select all

<?php
// include database connection file, if connection doesn't work the include file will throw an error message
include '../#####/db_files/db_connect.php';

$errors = array();
if (!empty($_SESSION))
{
    $email = filter_var($_SESSION['email'], FILTER_VALIDATE_EMAIL);
    if (!$email)
    {
        $errors['email'] = "Not a valid email address.";
    }
    else
    {
        $email = mysql_real_escape_string($_SESSION['email']);
        $query = "SELECT COUNT(EmailAddress) FROM ContactTbl WHERE EmailAddress = '{$email}'";
        list($email_count) = mysql_fetch_row(mysql_query($query));

        if ($email_count)
        {
            $errors['email'] = "That email address is already in use.";
        }
    }

    if (!$_SESSION['fname'])
    {
        $errors['fname'] = "First name cannot be empty.";
    }
    if (!$_SESSION['lname'])
    {
        $errors['lname'] = "Last name cannot be empty.";
    }
}

if (!empty($_SESSION) && empty($errors))
{
    $fname = mysql_real_escape_string(trim($_SESSION['fname']));
    $lname = mysql_real_escape_string(trim($_SESSION['lname']));

	$query = "INSERT INTO ContactTbl (FName, LName, EmailAddress) VALUES ('{$fname}', '{$lname}', '{$email}')";
    mysql_query($query) or die(mysql_error());
}
?>
Believe it (or not) I spent hours googling for information on how to most efficiently move $_POST data into global $_Session data. What I found was rather than declaring each $_POST variable as a $_SESSION variable one could use the following:

Code: Select all

$_SESSION=array_merge($_SESSION,$_POST);
This makes perfectly good sense to me... where ever possible one should keep things simple.

My next quandary was where to insert the code line. Since (in my mind, anyway) the register.php really is the "first stop" - it made since to insert the code in register.php, rather than register_post.php. But things are never as straight-forward as they seem. :?

Bottom line - I am able to write valid data to the table. But invalid data does not trigger an error message whether the code is inserted in register.php or register_post.php. I am really scratching my head here... what am I doing wrong?

Thanks Much - Pavilion
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Field Validation Question

Post by Pavilion »

This situation has been on my mind constantly. One (of many) questions that I can not resolve is the following?

If the above script is writing correct fname, lname and email to the appropriate table - then register_post2.php MUST be able to read data from register.php. If this is the case, then why do I need $_Session variables to execute errors upon invalid entry?

As I mentioned before, I am as interested in process as I am syntax. Simply understanding why variables work the way they work in php (vs. the way I have been used to them acting in classical Visual Basic) would go a long way towards helping me grasp the logic of php.

Thanks in advance for your help.

Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Field Validation Question

Post by Celauran »

The short of it is that you've got it backwards.

Code: Select all

<?php

session_start();

if (isset($_SESSION['errors']))
{
    $errors = $_SESSION['errors'];
}

?>

<!DOCTYPE htm>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
        <title>Contact Form</title>
        <style type="text/css">
            span.error
            {
                color: #F00;
                font-weight: bold;
            }
        </style>
    </head>
    <body>
        <form action="register_post2.php" method="post">
            <label for="fname">First Name</label>
            <input type="text" name="fname" />
            <?php if (isset($errors['fname'])): ?>
            <span class="error"><?php echo $errors['fname']; ?></span>
            <?php endif; ?><br />

            <label for="lname">Last Name</label>
            <input type="text" name="lname" />
            <?php if (isset($errors['lname'])): ?>
            <span class="error"><?php echo $errors['lname']; ?></span>
            <?php endif; ?><br />

            <label for="email">Email Address</label>
            <input type="text" name="email" />
            <?php if (isset($errors['email'])): ?>
            <span class="error"><?php echo $errors['email']; ?></span>
            <?php endif; ?><br />

            <input type="submit" value="Submit" />
        </form>
    </body>
</html>

Code: Select all

<?php

session_start();

// MySQL connection stuff goes here

unset($_SESSION['errors']);
$errors = array();
if (!empty($_POST))
{
    $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
    if (!$email)
    {
        $errors['email'] = "Not a valid email address.";
    }
    else
    {
        $email = mysql_real_escape_string($_POST['email']);
        $query = "SELECT COUNT(EmailAddress) FROM ContactTbl WHERE EmailAddress = '{$email}'";
        list($email_count) = mysql_fetch_row(mysql_query($query));

        if ($email_count)
        {
            $errors['email'] = "That email address is already in use.";
        }
    }

    if (!$_POST['fname'])
    {
        $errors['fname'] = "First name cannot be empty.";
    }
    if (!$_POST['lname'])
    {
        $errors['lname'] = "Last name cannot be empty.";
    }
}

if (!empty($errors))
{
    $_SESSION['errors'] = $errors;
    header('Location: register.php');
}

if (!empty($_POST) && empty($errors))
{
    $fname = mysql_real_escape_string(trim($_POST['fname']));
    $lname = mysql_real_escape_string(trim($_POST['lname']));

    $query = "INSERT INTO ContactTbl (FName, LName, EmailAddress) VALUES ('{$fname}', '{$lname}', '{$email}')";
    mysql_query($query) or die(mysql_error());
}

?>
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Field Validation Question

Post by Celauran »

Pavilion wrote:This situation has been on my mind constantly. One (of many) questions that I can not resolve is the following?

If the above script is writing correct fname, lname and email to the appropriate table - then register_post2.php MUST be able to read data from register.php. If this is the case, then why do I need $_Session variables to execute errors upon invalid entry?
Not quite. register_post2.php isn't reading anything from register.php; register.php is sending the data to register_post2.php via the POST method.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Field Validation Question

Post by Pavilion »

Celauran wrote:
Pavilion wrote:This situation has been on my mind constantly. One (of many) questions that I can not resolve is the following?

If the above script is writing correct fname, lname and email to the appropriate table - then register_post2.php MUST be able to read data from register.php. If this is the case, then why do I need $_Session variables to execute errors upon invalid entry?
Not quite. register_post2.php isn't reading anything from register.php; register.php is sending the data to register_post2.php via the POST method.
Firstly - your code works beautifully. A huge THANK YOU!! :D

Now for the big picture. As stated many times, I am as interested in process and logic as I am syntax. So... now that my two files are working I've many questions. I'll start with the $_SESSION lines of your code:

register.php

Code: Select all

<?php

session_start();

if (isset($_SESSION['errors'])) // is this line "grabbing the errors" so they can be "sent" to register_post2.php? The reason I ask is that you said in your last post that "register_post2.php isn't reading anything from register.php; register.php is sending the data to register_post2.php via the POST method." So.... I'm wondering ... is it not possible for the POST method to "send" empty fields, or invalid emails??
{
    $errors = $_SESSION['errors'];
}

?>

<!DOCTYPE html> // Also... why this line? Doesn't a simple <html> tag declare a document type?

<html>
Now for register_post2.php

Code: Select all

<?php
session_start();

// include database connection file, if connection doesn't work the include file will throw an error message
include '../####/db_files/db_connect.php';

unset($_SESSION['errors']); //does this line simply "release" the errors "sent" from register.php?
Also....

Code: Select all

if (!empty($errors))
{
    $_SESSION['errors'] = $errors; // what exactly is this line doing??? The error handling is above - so (from my current perspective) I can not see where this line is involved in error  handling at all?
    header('Location: register.php'); // lastly, everything I've read about "header" script is that it should come first in the document BEFORE any other code is executed. Obviously, this line works... but I am confused as to why this line can be at the end of the script and still execute?
}
These are all the questions I have right now. As I mentioned earlier I am at the "baby steps" level here. So... I am just trying to absorb this stuff in small bytes :wink:

Thanks again Celauran, and everyone else who has offered insight.

Pavilion
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Field Validation Question

Post by Celauran »

Pavilion wrote:Now for the big picture. As stated many times, I am as interested in process and logic as I am syntax. So... now that my two files are working I've many questions. I'll start with the $_SESSION lines of your code:

register.php

Code: Select all

if (isset($_SESSION['errors'])) // is this line "grabbing the errors" so they can be "sent" to register_post2.php? The reason I ask is that you said in your last post that "register_post2.php isn't reading anything from register.php; register.php is sending the data to register_post2.php via the POST method." So.... I'm wondering ... is it not possible for the POST method to "send" empty fields, or invalid emails??
{
    $errors = $_SESSION['errors'];
}
No, it's actually doing the opposite. It's checking the $_SESSION array to see if the key 'errors' has been set. The method declared in your form is what's sending the data to register_post2.php, which then checks for errors and redirects back here if necessary. Any errors discovered in register_post2.php are stored in the session and then retrieved here for display.
Pavilion wrote:

Code: Select all

<!DOCTYPE html> // Also... why this line? Doesn't a simple <html> tag declare a document type?
It does not. A valid DOCTYPE declaration is always required.
Pavilion wrote:

Code: Select all

unset($_SESSION['errors']); //does this line simply "release" the errors "sent" from register.php?
This 'clears' the session errors variable. If errors are discovered in this form submission, they will be written to session data anew. You don't want old errors 'hanging around' if you will. Say you submit the form with errors, are directed back to the form, fix the errors, and resubmit the form. If you don't unset the relevant session data, error text will be displayed the next time you visit the form, even before you submit it.
Pavilion wrote:

Code: Select all

if (!empty($errors))
{
    $_SESSION['errors'] = $errors; // what exactly is this line doing??? The error handling is above - so (from my current perspective) I can not see where this line is involved in error  handling at all?
Errors are being stored in the $errors array as they are discovered. Since we can't (nicely) pass that array back to register.php, we write its information to session data, which can be read from anywhere.
Pavilion wrote:

Code: Select all

    header('Location: register.php'); // lastly, everything I've read about "header" script is that it should come first in the document BEFORE any other code is executed. Obviously, this line works... but I am confused as to why this line can be at the end of the script and still execute?
}
Not before any other code is executed, but before any output is sent to the client.
Pavilion
Forum Contributor
Posts: 301
Joined: Thu Feb 23, 2012 6:51 am

Re: Field Validation Question

Post by Pavilion »

Celauran - thank you so much for you patience and for answering all of my questions. I've read through your answers, and must confess to only partially grasp what you are trying to convey. But, I'm sure with a bit of re-reading, googling and reading up on terms I don't fully understand - the essence of your answers will become clearer.

You should know that during this whole learning exercise I have intentionally left out the "password" field from all my files. My intent was that once, I had a fuller understanding of process and syntax - then I would go back and add in the "password" field as an exercise in learning and sort of "cementing" my understanding of both process and syntax. I just finished the process of adding "password" to both scripts and everything is functioning properly. Better, yet, for the most part I understood why and where to use the different elements. However - there was one area where I was simply using the previous syntax without a full understanding of why.

Code: Select all

<label for="password">Password</label> // this line sets up the label
<input type = "password" name="password" /> // this line sets up the input control and gives it a "password" type.
<?php if (isset($errors['password'])): ?> // Other than starting an "if" statement, I have no idea what this line is doing. If I had to guess... I'd say it was "grabbing" any error for later reference.
<span class="error"><?php echo $errors['password'];?></span> // I have no idea what this line is doing. It seems to be setting up an echo, but when I leave the password field blank - the only error message I receive is the one set up in register_post2.php. In addition to not understanding the reason for an "echo" - I also don't understand why the <span> tag is necessary - what is it doing?
<?php endif; ?><br />
Celauran - your assistance has been fantastic. From your perspective, I must be asking such basic questions. But.. trust me... I am learning. I've learned more about .php in the last week then I've learned in all my personal research over the past several months.

Thank you again - Pavilion
Post Reply