Data Form Validation and MySQL with Zend Framework

Data Validation with Zend Framework

You can download the lesson 7 start files here.

The definitive reference for Zend Validation can be found here.

The text is excellent at providing a step-by-step approach to building a robust web data form on Zend Framework.   The first step is to create the library.php file – we covered this in an earlier post.

The core validation code is set up in a separate php file from the form itself, called user_registration.php.    The initial set up of user_registration is to invoke on a POST (only run when the form is submitted), refer (require_once) to the library.php file for database and Zend library references, and set up and error return system using try/catch that will interact with the form input elements by echoing the error message.

Data input validation typically include 3 code snippets.

RegexFirst, in the core validation script, user_registration, we create an instance of a Zend_Validation… object, check the posted input data for validity and  if invalid we add an index to the $errors associative array that is indexed by field name and has a message for the form input.   Zend can validate for Alpha, but it’s better to use Regex, which is a text matching language.   Here is a David Powers tutorial in two parts about Regex.  Lesson 7 includes Alnum() Identical() and EmailAddress() validations and demonstrates how to add multiple validators to validation objects on pages 234-236.

Validation messageThe second snippet returns the error message to the input element.   It is a php script   wrapped in a span element on the actual form page, following the input element.   This PHP code checks if the form is in POST mode and if there is an index in the errors array with it’s input name, if so it echoes the error message alongside the input element.

Validation input preservationFinally we embed a PHP script into the value attribute of the input element in order to retain the value from the POST.   We do this regardless of whether it validated or not since there are multiple inputs in the form.  Notice the useful htmlentities() function, a useful piece of code explained on page 237.

Creating & using custom server behaviors

Dreamweaver includes prebuild server behaviors in PHP and other languages, and also allows web developers to create their own custom server behaviors, which, like code snippets, are available on available on all pages (that are php) on all sites on the system where the behavior is installed in the DW application setup.

A server behavior is nothing more than a core code block that can be explicitly placed before, after or into page elements or attributes.    Parameters and setup dialogs help make the server behaviors useful for multiple applications.  Following the examples on pages 238-244 is very useful.

Selecting & Inserting to MySQL with Zend Framework

Database validationValidations can include validators based on data in a MySQL database table.  Since we want to ensure unique usernames in the users table (we already set this up previously in a SQL unique index) we can have the form validator check the database before the input.  This code is added to user_registration following the username validation.  We run a sql select query on users and return an error if there is a result.    We pass the username from the POST data into the SQL Select using quoteInto() and pass it to the $dbWrite() database object we created in library.php. This sql object is passed to the fetchAll() select method.

Zend database insertThe php code to perform the insert is wrapped in a if (!errors) {} conditional – only insert if all input data validates according to its own rules as set by user_registration.php.  In fact we don’t even need SQL to perform the insert, just create an associative array indexed by  column name with the appropriate data values and call the insert() method of the Zend database object passing the table name and data array.   Magic!

Zend_Auth

We now create a script file called user_authentication.php that we will include on the login form to authenticate username and password information with the database.    The script starts almost exactly like user_registration.php, except instead of an $errors array to catch the exceptions, we are going to use a $failed boolean variable – there is only a thumbs up or thumbs down when you are authenticating a user.

We create an instance of the Zend_Auth object using getInstance() because it is a singleton (only one instance possible).   We create an authentication adapter object as a Database table lookup because we are using the MySQL user table as the authentication source.  Then we set properties for Identity and Credential to the Authentication adapter from the login form. If the login information authenticates with the database table info, your username and first and last name are stored into an array and you are taken to the members_only.php.  If the username or password are empty then it returns failed = TRUE without doing the database authentication.  This code is tricky, follow 249-252 closely.   At the end, you have a login form that is much more functional than the one built with server behaviors, and the techniques can be applied to many uses.

Next we need to create a script called restrict_access.php to require_once() into pages that we want to restrict, such as the members_only.php page in the example.   This script can be require_once()’d into any php page now.

Finally the textbook shows us how to personalize and create a logout on the internal page.   A working registration and login system!

6 comments for “Data Form Validation and MySQL with Zend Framework

  1. Mitch
    April 9, 2011 at 5:31 pm

    So my script will not write to the database and will not redirect. Library.php is functional. Im a bit confused? I even pasted the exact code from the finished example for the array and tried it and still get the same result. Any ideas?

    • April 10, 2011 at 10:29 am

      Mitch – Tell me what page isn’t working, I can take a look at your code.

  2. Mitch
    April 10, 2011 at 1:54 pm

    http://student.santarosa.edu/~mvetter/AdvDw/add_users.php

    the code to validate input works,
    where it breaks is when you fill the form correctly and hit submit.

    -Thanks

    • April 10, 2011 at 9:12 pm

      Mitch – I got your page working, there were several problems. You renamed the form input from surname to family_name, but didn’t change it in the insert area code of user_reg. You also copied the code for the username database lookup, which refered to the $dbRead connection, which we did not create in library.php

  3. Mitch
    April 11, 2011 at 9:52 pm

    Awesome thanks!

  4. April 18, 2011 at 12:34 pm

    Could you take a look at my lesson seven and perhaps tell me what the heck is wrong with it?! I can’t see what the problem is.
    Thank you.

Comments are closed.