PHP DevCenter
oreilly.comSafari Books Online.Conferences.

advertisement


PHP With HTML Forms
Pages: 1, 2

Error processing

The script contains a function CheckResults() to validate required fields. There is a series of statements checking form variables. A few error-checking statements are:



	if (!$FirstName) $ErrorArray[] = "No first name entered";
$OScount = count($OperatingSystem);
if (!$OScount) $ErrorArray[] = "Select at least one Operating System";

One element of array $ErrorArray is loaded for each error. The error process function may be used as a template to perform more ambitious checking.

Finally, the function returns 1 if there are errors present and 0 if there are no errors with the following:

  $ErrorCount = count($ErrorArray);
  return ($ErrorCount) ? $ErrorsPresent : $NoErrors ;

If there are errors, the function DisplayErrors() is called, passing the array containing the errors. After displaying a nicely formatted list of errors, the form is again displayed with previously entered values displayed.

A word of caution: Several of the functions in this script use the count() function on a passed array to determine the number of array elements. The developed count determines the number of required buttons or boxes and, hence, the number of iterations. Be careful if zero is passed as a parameter as count(array(1,1,1,1)); returns 4, but count(array(1,0,1,0)) returns 2.

Program flow

Writing a good program involves decomposing a problem into small logical units. When faced with subprogram code generation, give serious thought to generalizing the function to solve a class of problems, not just a specific problem.

As stated in the last segment, a good program, as opposed to a program that simply works, has these characteristics:

  1. It does what it is supposed to do, under all circumstances.
  2. It is easy to modify by someone other than the original programmer.
  3. It's efficient in the use of resources, both human and computer.

In keeping with these lofty goals, a good program should have a main line that calls subprograms to do all the hard work. The main body of the program should therefore just be logic components required to solve the task at hand. In form-two.php, the all-important main line is simply:

<?php

makehtmltop("Form Series","Example Two");

empty($firstpass) ?	# first pass if empty
  showform() :    	# display the form if first pass
  $errors = checkresults($errorarray); # check results if not first pass

($errors) ? # are there form processing errors?
  displayerrors($errorarray) : # display errors
  showresults();		  # display results

exit; # all done

Here's what happens. Put up an HTML top of page. If it's the first pass, display the form. If it's not the first pass, check to make sure all fields conform to validation rules.

If there were any errors, display the errors, and redisplay the form populated with any values from the previous submission. Show the final results if there are no errors.

So there you have it, fellow phanatics, a group of functions to make your form generation life easier. If you enhance any of these functions, I would very much like to hear about them.

As promised, we will take another look at the $globals array before closing this session. The new array dumper is yet another generalized function.

The $GLOBALS array revisited

As mentioned in our last episode, the $GLOBALS array contains environment variables, both GET and POST data from forms, cookie variables, and server variables. As such, the possibilities of naming conflicts are very real. If you have a cookie variable called $status and a form variable likewise named $status, what happens when you ask the real $status to stand up? The answer is, it depends.

The file php.ini has a variable called variables order. The default setting is:

variable_order  = "egpsc"

Array elements for $GLOBALS are loaded from left to right based upon the configuration setting in php.ini. If the initial installation default setting on your system is still intact, cookie variables would be loaded last and therefore have highest priority. Be especially alert for naming duality when enhancing third-party scripts and using objects.

You can be totally safe if you access the individual array components. If your form uses the POST method, its variables may be accessed using the HTTP_POST_VARS array. If the NAME parameter of a form field is FirstName and you use the GET method, the data is available in $HTTP_GET_VARS[FirstName].

Now back to my bug. The individual $GLOBALS array elements may themselves be arrays. The solution to correctly displaying an array of arrays is nested loops. Let's build an array dumping function, DumpArray(), for displaying any two-dimensional array. Here is the call and the function header:

	DumpArray("GLOBALS",$GLOBALS);

function DumpArray($ArrayName,&$Array)

The function required two parameters, the literal name of the array to be processed and the variable containing the array. When communicating with a subprogram, variables are passed in one of two ways: call by value and call by reference. When calling by value, a local copy of the original is established within the subprogram. Changes made to the local copy are not reflected in the original and die when the subprogram is exited. On the other hand, when calling by reference, a pointer to the original variable is passed, and any changes made to the variable in the subprogram are actually being made to the original variable.

Both methods have advantages. You may want to manipulate the local copy and not change the original. In this case, call by value. Conversely, the data structure to be passed to the subprogram may be large. If a large data structure is to be modified in a function and returned, it must be copied twice -- once when the function is called and again when it's returned.

In this function, I have chosen to call by reference, since the array to be displayed could be quite large. If you choose to call by reference, the syntax of either the calling or receiving parameter must start with an &. I like to have the subprograms parameter indicate the reference since it only has to be done once.

The heart of the new dumping function is:

foreach ($Array as $Key=>$Value){
  if (is_array($Value))

Source code

Source code for form-two.php

Source code for dump-globals.php

The passed array is traversed as before. Before displaying a component, it is tested by the is_array() function. If it's an array, an inner loop is started; if not, the element is displayed. You can see the output of a script that calls the DumpArray() function passing a reference to the $GLOBALS array by clicking here.

How about a three-, or more, dimensional array, you might reasonably ask. This would be a perfect spot for a function making recursive calls. (A recursive function is one that calls itself.) We will revisit the N-dimension array problem is a future episode.

Urb LeJeune is a 25-year programming veteran with over 10 years of Internet experience thrown in for good measure.


Read more PHP Forms columns.

Discuss this article in the O'Reilly Network PHP Forum.

Return to the PHP DevCenter.

 




Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!


Sponsored by: