Page 1 of 5

Field Validation Question

Posted: Thu Feb 23, 2012 7:02 am
by Pavilion
Hello Everyone:

Although I've 20 years of experience building classical databases, I'm a newbie to php. I have figured out some of the basics, but need help with field validation. The affected code follows:

File Name: register.html

Code: Select all

<body>
<form action="[b]register_post.php[/b]" method="post">
First Name: <input type="text" name="FName" />
Last Name: <input type="text" name="LName" />
Email: <input type="text" name="EmailAddress" />
<input type="submit" />
</form> 
</body>
Submit file name: register_post.php

Code: Select all

<?php
include '../####/db_files/db_connect.php';

 if (!$link)
 {
 die('Could not connect: ' . mysql_error());
 }

 mysql_select_db("m1stcontact", $link);

$sql="INSERT INTO ContactTbl (FName, LName, EmailAddress)
VALUES
('$_POST[FName]','$_POST[LName]','$_POST[EmailAddress]')";

 if (!mysql_query($sql,$link))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";
echo "<br />";

// following syntax queries table for data and echos it.
$result = mysql_query("SELECT * FROM ContactTbl ORDER BY LName, FName");

while($row = mysql_fetch_array($result))
  {
  echo $row['FName'];
  echo " " . $row['LName'];
  echo " " . $row['EmailAddress'];
  echo "<br />";
  }

//following statement closes connection to databasee
mysql_close($link)
?>
The code works. But... it needs field validation. Specifically, I don't want users to be able to enter duplicate email addresses. What do I need to do with this code to prevent duplicate email addresses?

Thanks Much:

Pavilion

Re: Field Validation Question

Posted: Thu Feb 23, 2012 7:31 am
by Celauran
Change the email field in the database to unique?

What it also needs is sanitization. Please have a look at mysql_real_escape_string at the least, or consider using prepared statements.

Re: Field Validation Question

Posted: Thu Feb 23, 2012 11:05 pm
by Pavilion
Celauran wrote:Change the email field in the database to unique?

What it also needs is sanitization. Please have a look at mysql_real_escape_string at the least, or consider using prepared statements.
Celauran - Thank you for your response.

You gave some excellent advice - and with a bit of searching I was able to figure out how "bring it all together". As it stands now, the code is as follows:

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';

// test code to find duplicate email addresses
// Query database to check if there are any matching Email addresses 
$query = "SELECT * FROM ContactTbl WHERE EmailAddress='{$_POST['EmailAddress']}'";
$result = mysql_query($query);

// mysql_num_rows tests for the number of matchiing rows.
$num_rows = mysql_num_rows($result);

if ($num_rows>"0")
	echo "Someone has already registered with this email address.";
else

// insert script inserts values from the register.html input fields into the appropriate table fields
$sql="INSERT INTO ContactTbl (FName, LName, EmailAddress)
VALUES
('$_POST[FName]','$_POST[LName]','$_POST[EmailAddress]')";

 if (!mysql_query($sql,$link))
  {
  die('Error: ' . mysql_error());
  };

//following statement closes connection to databasee
mysql_close($link)
?>
For the most part it works. When the row count is 0 the record is inserted into the database with no problem. The only thing wrong is that Error: Query was empty follows my echo statement if the row count is >0. Following is the echo message and the error:
Someone has already registered with this email address.Error: Query was empty
Do you have any idea why the error is showing up with my echo statement? If I simply echo the row count - it shows 0 and nothing else - no error - no nothing. Only when I echo a message about duplicate email addresses, does the error message appear. :?

Thank you for your help.

Pavilion

Re: Field Validation Question

Posted: Fri Feb 24, 2012 6:40 am
by Celauran

Code: Select all

<?php

$sql = mysql_connect('localhost', '****', '****');
mysql_select_db('****');

$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);
}

?>

<!DOCTYPE html>
<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="" 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>

Re: Field Validation Question

Posted: Sat Feb 25, 2012 9:16 pm
by Pavilion
Celauran - Thank you for posting this script. I do want to work with it and get my head around everything that is going on inside the code.

My first question is pretty fundamental. So far - in all my studying on php - I was under the impression that one should keep html script separate from php script. The protocol I've learned is to create an html file and on the submit, call up the php processing script.

But... if I'm reading your contribution correctly ... you are using html in the same file as php??? Is this an accurate observation?

I'm REALLY new to php/html here... so please bear with me.... but how common is it to use php/html in the same file. Do most people put their html in one file and php in another, or do most people combine the two in one file. I guess I'm asking what the industry standard is?

Thanks so much for your patience with my elementary understanding.

Oh... one last question... if the php and html are combined in one document then what file extension do you use, .php or .html? If you use .php wouldn't the last line of the script have to be ?>?
Pavilion.

Re: Field Validation Question

Posted: Sun Feb 26, 2012 7:06 am
by Celauran
Pavilion wrote:But... if I'm reading your contribution correctly ... you are using html in the same file as php??? Is this an accurate observation?
Yes, that's right.
Pavilion wrote:I'm REALLY new to php/html here... so please bear with me.... but how common is it to use php/html in the same file. Do most people put their html in one file and php in another, or do most people combine the two in one file. I guess I'm asking what the industry standard is?
How common is it? Extremely. That doesn't make it best practice, mind you. I threw that together quickly solely for the sake of example. What you mix and what you keep separate really depends on the size of the project at hand. Using an OO MVC framework for a simple contact form, for example, is pretty silly. For a full site, using an OO MVC approach makes more sense and generally results in cleaner, more maintainable code. My general rule of thumb is that flow control statements are acceptable in the views, but that's about it.

Pavilion wrote:if the php and html are combined in one document then what file extension do you use, .php or .html? If you use .php wouldn't the last line of the script have to be ?>?
You use the .php extension, otherwise PHP will ignore the file (unless you get into some .htaccess wizardry). In a pure PHP file, the closing ?> is optional and I tend to omit it. When the file is a combination of PHP and HTML, you need the delimiters to show where one ends and the other begins.

Re: Field Validation Question

Posted: Sun Feb 26, 2012 7:42 am
by Pavilion
Hello Celauran
What you mix and what you keep separate really depends on the size of the project at hand. Using an OO MVC framework for a simple contact form, for example, is pretty silly. For a full site, using an OO MVC approach makes more sense and generally results in cleaner, more maintainable code. My general rule of thumb is that flow control statements are acceptable in the views, but that's about it.
OK ... I think I understand what you are saying. Although the term MVC is entirely new vocabulary as well as the phrase "flow control statements". I know "OO" is Object Oriented. :D. But, I'm not sure if "view" means the same thing to you that it means to me. I'm used to thinking of "view" in the context of MySQL and SQL.

But.. in essence.. and correct me if I'm wrong. Mixing html/php in simple 1-2 page applications is fine... but the larger the application the more important it is to separate your files into .php and .html? (That is what my gut has been telling me as well :) )
You use the .php extension, otherwise PHP will ignore the file.
This is very useful information, thank you. It tells me that PHP dominates and HTML works within PHP.
In a pure PHP file, the closing ?> is optional and I tend to omit it. When the file is a combination of PHP and HTML, you need the delimiters to show where one ends and the other begins.
I knew about the delimiters, but did not know that one could omit the closing ?> ... It only makes sense though. Back to my previous revelation... that PHP dominates... if one is working within a PHP environment, then the assumption will be that everything is .php unless otherwise noted.

Thank you again for your help in exploring process as well as syntax.

I do want to play with your code somewhat... especially the way you check for valid email addresses and catch errors. I will keep my html in a separate file because I am planning a larger application and these objects may become part of that application.

Thank you again - Pavilion

Re: Field Validation Question

Posted: Mon Feb 27, 2012 6:14 pm
by Pavilion
Hello Celauran - thank you for this script suggestion... I've some questions...

Code: Select all

[quote]<?php

$sql = mysql_connect('localhost', '****', '****');
mysql_select_db('****');

$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.";
    }
}[/quote]
Does this part of the script search for empty post contributions and throw error messages requiring input? If so... the whole email script is confusing because the commands seem to be geared towards having a value to test. The email script is testing both for valid email addresses and for duplicate email addresses. This can't be done with an empty post... :?

The second part of your code seems pretty straight-forward. It's trimming the data and inserting it into the ContactTbl

As mentioned in an earlier post, I will keep my html in a separate file from the php post file. But... I do have some questions about all the php in your html script. Is the php passing data to the main php processing script above? Specifically what does this line do?

Code: Select all

<?php if (isset($errors['email'])): ?>
And what does this line do?

Code: Select all

<span class="error"><?php echo $errors['email']; ?></span>
Thanks for your patience. I know these are very basic questions, but that's where I'm at right now - a very basic level.

Pavilion

Re: Field Validation Question

Posted: Mon Feb 27, 2012 10:08 pm
by califdon
You're in good hands with Celauran giving you advice and instruction, but I just wanted to add a few thoughts that might be of help to you.

As Celauran said, mixing PHP and HTML in the same file is probably the most common approach for relatively small web applications. Among other advantages, it reduces the number of separate HTTP requests to the server and is thus slightly more efficient.

I suggest that you think of the file extension question in the following way, rather than as PHP being "dominant" over HTML: PHP is a language that is parsed and executed by the web server (e.g., Apache or IIS), which is configured by default to parse a file and execute any PHP code in it only if the file has a .php extension. There are ways to configure it otherwise, but rarely any reason to do so.

Now, about your script(s), most developers would probably advise you to do data validation BOTH in the client browser, using Javascript, AND in the server, using PHP, for best operation. The Javascript routines can require the user to complete any required fields before submitting the form to the server, thus avoiding unnecessary submissions to the server. Such routines can also check for valid ranges of values or formats in some applications. This is a first-step validation that many developers believe is best practice. You must be aware of the behavior in those cases where the user's browser has been set to disable Javascript, though.

Finally, I personally avoid EVER using form data directly (that is, $_POST['xxx']) in a PHP script without first sanitizing the data and assigning it to a variable. Then I know that when I use those variables, they have previously been sanitized.

I hope these remarks will be of value.

Re: Field Validation Question

Posted: Wed Feb 29, 2012 7:28 am
by Pavilion
califdon wrote:You're in good hands with Celauran giving you advice and instruction, but I just wanted to add a few thoughts that might be of help to you.

As Celauran said, mixing PHP and HTML in the same file is probably the most common approach for relatively small web applications. Among other advantages, it reduces the number of separate HTTP requests to the server and is thus slightly more efficient.

I suggest that you think of the file extension question in the following way, rather than as PHP being "dominant" over HTML: PHP is a language that is parsed and executed by the web server (e.g., Apache or IIS), which is configured by default to parse a file and execute any PHP code in it only if the file has a .php extension. There are ways to configure it otherwise, but rarely any reason to do so.
Thank you califdon - this information does help.
Now, about your script(s), most developers would probably advise you to do data validation BOTH in the client browser, using Javascript, AND in the server, using PHP, for best operation. The Javascript routines can require the user to complete any required fields before submitting the form to the server, thus avoiding unnecessary submissions to the server. Such routines can also check for valid ranges of values or formats in some applications. This is a first-step validation that many developers believe is best practice. You must be aware of the behavior in those cases where the user's browser has been set to disable Javascript, though.
And now ... I'm starting to see where Javascript comes into play. Actually, this point leads me to another question. While doing some research/learning on HTML, I found the following snipit of code:

Code: Select all

Email: <input type="email" name="EmailAddress" />
Specifically input type="email" was new information. I was always using input type = "text" or "date". So.... I tested input type="email" and it is a way of validating data before submitting. So... why the Javascript? Why add one more level or layer of scripting?
Finally, I personally avoid EVER using form data directly (that is, $_POST['xxx']) in a PHP script without first sanitizing the data and assigning it to a variable. Then I know that when I use those variables, they have previously been sanitized.
This makes sense. It is the way I operate in building classical databases. But... what is confusing for me (since there are multiple languages involved in web database development) is how one declares variables. In classical database development - I declare my variables within specific routines. It is rare that I have to globally declare a variable. But in this context, it almost seems to me that variables are more useful if they are defined globally.

At any rate, within this specific example.... would declaring $fname, $lname and $ email before the IF statement be appropriate. Or ... since this statement is testing for empty posts first, is it better to declare within the IF statement, as Celauran has done?
I hope these remarks will be of value.
Yes - your remarks are very helpful. As I mentioned earlier... I am as interested in method as I am in syntax.

Thanks Much: Pavilion

Re: Field Validation Question

Posted: Wed Feb 29, 2012 8:40 am
by Celauran
Scope isn't really an issue here as you're using purely procedural code; no functions, no objects. Everything is in the same scope. You can declare all your variables at the top of the script and then initialize them later if you prefer. So long as you don't try to access variables which haven't yet been defined, things will work the same either way.

A note about input type=email: it's HTML5, which means it won't be supported in all browsers (namely IE). One of the advantages of using JS form validation is that it works client side, so can potentially save several server requests. Note, though, that client-side validation is very much in addition to server-side validation, and not in lieu of.

Re: Field Validation Question

Posted: Wed Feb 29, 2012 12:06 pm
by califdon
Celauran wrote:Note, though, that client-side validation is very much in addition to server-side validation, and not in lieu of.
Yes, that must be emphasized. A typical hacker exploit would be to bypass your Form entirely, using cURL or other mechanism to send data directly to your server, so you can't rely on client-side operations to defeat hacking. On the other hand, client-side validation can resolve many common user errors without requiring any server involvement. I would suggest that you think of this in the following terms:
  1. Client-side (Javascript): correcting benign, simple user errors before submitting data
  2. Server-side (PHP): protection against malicious exploits and anything requiring server-side data
Because PHP is mostly used just to generate a stream of HTML/CSS/Javascript code to be sent to a browser, there is less need for the kind of variable scoping and declaring that other languages often have to provide for. As Celauran said, your example here doesn't really require such distinctions, so it is perfectly OK to use variables in the simplest syntax possible. Unless you have a considerably more complex script, there is nothing wrong with just instantiating a variable when you need to assign a value, and don't worry about global scope (which, as Celauran said, is all there is in this example). When you define PHP functions, scope does come into play, as well as when you define objects, but that isn't the case here.

Re: Field Validation Question

Posted: Wed Feb 29, 2012 12:33 pm
by DjituS
first use regular expression to check whether it is a valid email or not. because, it may be any sql injection.
secondly, for checking it is not duplicate email id run sql query comprising statement "like", and then you will find what you want.
generally, giving key 'unique' in mysql database will never let user to enter duplicate value. but it not will be good for users interface.

Re: Field Validation Question

Posted: Thu Mar 01, 2012 7:42 am
by Pavilion
Hello Celauran (and everyone else):

Firstly - thank you so much for all the insight you've given me on process. It is just as important as proper syntax. Almost 20 years of working with classical databases have taught me the importance of clean and efficient practices. I do want to continue a fuller discussion with all of you on process. But... right now my immediate problem in syntax.

Celauran - as I mentioned in an earlier post - I really do want to keep my html and php scripts in different files (back to process). I am planning a larger application and may very well use what I am learning here. So... I may as well learn to do it properly.

In between all my client commitments, I've been able to work with the script you provided earlier. I put part of it in an html file and the other part in a php file. The files follow:

register2.html

Code: Select all

<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="" 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 '../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);
}

?>
The problem ... whatever I put in... whether it be:
  • Clean and new email address
  • invalid email address
  • null fname
  • null lname
  • valid total entry - valid fname, valid lname, valid email


All I am getting in return is a blank white screen after hitting submit.

No records are added to the database - when data entry is valid.

No errors are thrown when data entry is invalid.

I am totally confused :?

Any help you can give me would be appreciated. I realize breaking your original code into two files may be causing some problems, but it seemed a pretty straight-forward exercise.

Thanks Much - Pavilion

Re: Field Validation Question

Posted: Thu Mar 01, 2012 8:22 am
by Celauran
Breaking it into two files did indeed break it, at least insofar as the error reporting goes. Error checking is done after the form is submitted. If you want to display the errors, you'll need to write them to session data and redirect back to the page containing the form in order to display them.

As for valid data not being inserted into the database, that is bizarre. Let's check for mysql errors.

Change this

Code: Select all

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

Code: Select all

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