Examples


On the CD Let us consider several common items of information that could be input by a person sitting at the client computer. The projects demonstrated here involve using regular expressions to validate user input and regular expressons and other patterns to find records in databases. The CD-ROM contains the code for the projects in the folder named chapter11code.

A postal zip code for the United States consists of five digits, or five digits followed by a hyphen and then four more digits. A regular expression for a zip code needs to do the following:

  • Anchor the pattern at the start with the caret.

  • Define a sub-pattern that specifies exactly five digits.

  • Define a sub-pattern that specifies a hyphen followed by exactly four digits. This sub-pattern is to be present zero or one time, requiring the question mark symbol.

  • Anchor the pattern at the end with the dollar sign.

With this reasoning, the regular expression for a zip code is:

    ^[0-9]{5}(-[0-9]{4})?$

A common input type is the specification of quantity for an order. Assume that this is input as a string as opposed to a drop-down box or a component that allows the user to click to increase a quantity. The reasoning used to generate this pattern is:

  • Anchor the pattern at the start with the caret

  • Require one digit from 1 to 9

  • Define the sub-pattern as zero to any number of digits

  • Anchor the pattern at the end with the dollar sign

With this reasoning, the regular expression is:

    ^[1-9][0-9]*$

Suppose you want to detect the presence of one of several possible words in a string. Perhaps you need to design a form for customer complaints, and you want to direct all complaints about “quality” and “performance” to one specific department. You would do a regular expression check using the pattern:

    (quality)|(performance)

In this example, you probably would choose to make the test case-insensitive and, consequently, use the appropriate function in PHP or the i following the slash in JavaScript.

For a last example, suppose you want to check for a credit card number that is four groups of four numbers. You have decided to permit either 16 contiguous numbers or four groups of four numbers separated by a blank or by hyphens. People need to choose one or the other—they cannot put in eight numbers and a blank and then eight more. The reasoning to generate this pattern is:

  • Anchor the pattern at the start with the caret.

  • Define as one sub-pattern 16 digits.

  • Define as a sub-pattern four digits. Combine it with a sub-pattern of a blank or a hyphen repeated to get the full 16 digits plus three intervening symbols.

  • Make the two previous sub-patterns alternates using the | symbol.

  • Anchor the pattern at the end with the dollar sign.

The resulting regular expression is:

    ^([0-9]{16})|( [0-9]{4}( |-)[0-9]{4}( |-)[0-9]{4}( |-)[0-9]{4})$

Validation in PHP

The form shown in this example includes name, number of tickets, zip code, and a destination, given via a drop-down menu. The number of tickets and the zip code are validated using the regular expressions discussed in the previous section. However, the name also requires validation. Specifically, this script, as is typical, will check to make sure that this field is not blank. It is not a rigorous validation, but the situation does often occur that someone submits a form and leaves out information, so you need to incorporate checking for this situation in your code.

The destination value is not validated. A legal value is always sent to the handler because there is a default value. However, the message produced by the system tells the person what destination was selected. In most applications involving money transactions, the customer is given a chance to confirm the information, so if the default value was not correct, the customer could correct the information.

The application consists of an HTML form script and a handler script. The HTML form script will be the same for both the PHP and ASP/JavaScript versions, except for the file specified in the action attribute of the form tag. The PHP script for displaying the form, with explanation, is shown in Table 11.1.

Table 11.1: PHP Script to Display Form

<html><head><title>Travel</title></head><body>

Usual HTML

<h1>Travel</h1><p>

Heading

<hr>

Horizontal rule

<form action="midt.php" method=get><br>

Directs the form input to the midt.php file

Name: <input type=text name="name"><br>

Input file for the name

Number of tickets: <input type=text name="ticketno"><br>

Input file for the number of tickets

Zip code (5 digit or 5+4 format): <input type=text name="zip"><br>

Input file for the zip code

Select destination <br>

Text preceding drop-down menu

<select name="state">

Start of drop-down menu

<option value="NY">NY</option>

NY option

<option value="NJ">NJ</option>

NJ option

<option value="IL">IL</option>

IL option

</select><br>

End of drop-down menu

<input type=submit value='SEND'><input type=reset value='RESET'>

Submit button tag

</form></body></html>

Usual HTML close

The HTML produces the form, shown in Figure 11.1 with the fields filled in.

click to expand
Figure 11.1: Travel form filled in.

The PHP handler is shown in Table 11.2.

Table 11.2: PHP Script for Server-Side Validation of Form Data

<html><head><title>ticket checker</title></head><body>

Usual HTML start

<?php

Start PHP

$ticketchk="^[1-9][0-9]*$";

Define the pattern to check for a number greater than 0

$zippattern="^[0-9]{5}(-[0-9]{4})?$";

Define the pattern for a zip code: 5 digits plus option of 5-4

$oksofar=true;

Start the $oksofar variable to be true

if ($name=="") {

Check if name is empty string

$oksofar=FALSE;

This is a problem. Flip $oksofar to false

print("<br>Please enter a name. ");}

Output an error message

if (!eregi($ticketchk,$ticketno)){

Compare the number of tickets input with the pattern. If it does not match…

$oksofar=FALSE;

This is an error. Flip $oksofar

print("<br>Please enter number of tickets. ");}

Output an error message

if (!eregi($zippattern,$zip)) {

Compare the zip code inputted with the pattern. If it does not match…

$oksofar=FALSE;

This is an error. Flip $oksofar

print ("<br>Zip code given, $zip, is not in standard format.");

Output an error message

}

End if

if ($oksofar) {

Check $oksofar—is it still true

if ($ticketno==1){

Do test to determine if ticketno is 1 or not

print ("<br><font size=12><b>Thank you, $name.<br> You bought a ticket to $state.</b></font>");}

Print out message for buying one ticket

else {

Else (it was more than 1)

print ("<br><font size=12><b>Thank you, $name.<br> You bought $ticketno tickets to $state.</b></font>");}

Print out message for more than one ticket

}

End if checking $oksofar

?>

Close PHP

</body></html>

Usual HTML close

When the SEND button is clicked in the HTML form properly filled out as shown, the screen shown in Figure 11.2 appears.

click to expand
Figure 11.2: Display of Screen Capture of Response to Validated Data

Examine the query string up in the location field to see the values actually sent to the handler. Notice that NY is sent as the state value, even though it was not clicked. It is the default. The handler correctly determines that the input is valid and prints a message.

What if the input indicated in Figure 11.3 was typed into the form?

click to expand
Figure 11.3: Form with incorrect data.

The response by the handler is shown in Figure 11.4.

click to expand
Figure 11.4: Response in case of errors.

The handler has detected the two errors. The message concerning the number of tickets could be improved.

Validation in ASP/JavaScript

The same application will be shown using JavaScript. The HTML form is identical to the one just shown for PHP, except for the form tag, which, in this case, points to an ASP file:

    <form action="midt.asp" method=post> <br>

The handler for checking the data is shown in Table 11.3.

Table 11.3: ASP/JavaScript Script to Validate Form Data

<%@ Language=JavaScript%>

Sets JavaScript as language

<html><head><title>ticket checker</title></head><body>

Usual HTML open

<%

Start ASP

var name=String(Request.Form("name"));

Extract form input to define name

var ticketno=String(Request.Form("ticketno"));

Extract ticket number input

var zip=String(Request.Form("zip"));

Extract zip code input

var state=String(Request.Form("state"));

Extract state input

var ticketchk=/^[1-9][0-9]*$/;

Define pattern to check ticket number

var zippattern=/^[0-9]{5}(-[0-9]{4})?$/;

Define pattern to check zip code

var oksofar=true;

Set oksofar to start as true

if (name==""){

Check if name was not given

oksofar=false;

Flip oksofar to be false

Response.Write("<br>Please enter a name. ");

Output error message

}

End if test

if (!ticketno.match(ticketchk)) {

Check ticket number

oksofar=false;

Flip oksofar

Response.Write ("<br>Please enter number of tickets. ");

Output error message

}

End if test

if (!zip.match(zippattern)) {

Check zip code

oksofar=false;

Flip oksofar

Response.Write ("<br>Zip code given, "+zip+", is not in standard format.");

Output error message

}

End if test

if (oksofar) {

Check if oksofar still true

if (ticketno==1){

Check if just 1 ticket (NOTE this is two equal signs to check equality)

Response.Write ("<br><font size=12><b>Thank you, "+name+".<br> You bought a ticket to "+state+".</b></font>");}

Output appropriate message for one ticket

else {

Else other possibility: more than one ticket

Response.Write ("<br><font size=12><b>Thank you, "+name+".<br> You bought "+ticketno+" tickets to "+state+".</b></font>");}

Output appropriate message for more than one ticket

}

Close else clause

%>

End ASP

</body></html>

Usual HTML end

SQL Queries

The previous examples make use of the PHP language and JavaScript. You might decide that you want to make an SQL query in which you want to find records based on a pattern match of field values instead of equality or inequality. For example, users might want to search for the warnings in the database that contain a specific word, but could contain other things. The form to request this information is shown in Figure 11.5.

click to expand
Figure 11.5: Screen capture requesting problem term.

If you filled out the form as indicated in Figure 11.6, you might expect to get a response with all the shows having any warnings containing the “problem” item. Figure 11.7 shows the response.

click to expand
Figure 11.6: Problem entered into form.

click to expand
Figure 11.7: Screen capture for response for warnings containing the problem term.

The reason field contained the “problem,” but did not exactly match it.

The SQL standard provides the LIKE operator and its two wildcards: percent sign for any number of any character, and underscore for exactly one character. In addition, MySQL provides REGEXP for regular expression matching. The next two sections demonstrate the use of these operators in the PHP/MySQL system and the ASP/JavaScript Access system. The critical component of these two alternatives is the database. MySQL provides more functionality than Access, so to get the response just described, you need to do some work.

MySQL LIKE and REGEXP

The following script accepts input from the person sitting at the client computer and uses the text in an SQL statement using the LIKE operator. The Select query requests title, description, and reason fields from shows that have warnings with reasons that match the data. The records from the recordset produced are displayed.

The code needs to detect the situation of no records matching. This requires use of the PHP function mysql_num_rows. Because this test needs to be done after the query, you need to resist the temptation to output the HTML with the initial table tags at the very start of the script.

This script will serve to handle the form and display the form so it contains an if statement checking if the form has been submitted using a hidden input tag.

Since the query is complex, the code in Table 11.4 constructs the query in three steps and also displays it. This is all for the purposes of easy debugging. You can change it once your script is working.

Table 11.4: PHP Script to Find Warnings with Specified Term

<html><head><title>Find shows with certain warnings</title></head><body>

Usual HTML start

<h1>Favorites<br></h1>

Heading

<?

Start PHP

if (@$submitted) {

Check if this is the handling part of the script

include("openfirstdb.php");

Include the code that makes connection to the database

$sq ="SELECT f.title, f.description, w.reason ";

Construct the query in several steps

$sq = $sq . " from favorites as f, warnings as w where f.favorite_id = w.favorite_id ";

Add to query

$sq = $sq . " and w.reason LIKE '$problem'";

Add to query

print("Query is $sq<br>");

Print out query for debugging purposes

$rs = mysql_db_query($DBname,$sq,$link);

Perform the query to get a recordset in $rs

if (mysql_num_rows($rs)==0) {print ("No warnings match: $problem. Use a more general pattern."); } else {

Check for no matches. If so, print out a message

print("<h3>Shows with indicated problem</h3><br>");

Output heading

print("<table border='1'><tr><td>Titles</td><td>Descriptions</td>");

Output table tags

print("<td>Reason</td></tr> ");

More table tags

print("\n");

Output line break for the HTML

while ($row=mysql_fetch_array($rs)) {

While loop to iterate through the recordset of matches. This will stop when no more rows; that is, records in the recordset

print("\n");

Output line break for the HTML

print("<tr><td>");

Output table tags

print($row["title"]);

Output the title

print("</td><td>");

Output table tags

print($row["description"]);

Output the description

print("</td><td>");

Output table tags

print($row["reason"]);

Output the reason

print("</td></tr>");

Output table tags closing off row of table

} // end while

End of while

print("</table>");

Output closing table tag

} // ends else, rows in recordset

End the else clause for it not being the case that there were no records. There were records

mysql_close($link);

Close connection

$submitted = false;

Reset the submitted variable

print("<a href='sfindwarnings.php'>Try again </a>");

Output a hyperlink to allow user to try again

}

End the if form was submitted clause

else {

Start the else clause: form needs to be shown

?>

Close PHP

<h2>Find shows with warnings containing specific problem </h2><br>

Straight HTML heading

<form action="sfindwarnings.php">

Form tag

Describe problem <input type='text' name='problem'><br>

Input tag for problem string

<input type='hidden' name='submitted' value='true'>

Hidden input tag

<input type='submit' value='Find'>

Button

</form>

Close form

<?

Restart PHP

}

Close else clause

?>

Close PHP

</body></html>

Usual HTML close

If you try this script and want to check for a word contained in the reason field of a record in warnings, you will need to type in the wild card percent sign symbol before and after the term. Try this script with your database using terms that are contained in the reason fields. In our example, using “Nudity” would not return any records. In contrast, typing in “%Nudity%” would. You would need to use the next script or do some other manipulation of the user input to get the results indicated in the previous screen shots.

The MySQL system supports the operator REGEXP. Let us modify the script to make use of this operator. The one difference from the preceding example would be the definition of the query:

    $sq ="SELECT f.title, f.description, w.reason ";     $sq = $sq . " from favorites as f, warnings as w";     $sq = $sq . " where  f.favorite_id = w.favorite_id ";     $sq = $sq . " and w.reason REGEXP '$problem'";

In this case, the test for a specific word within the reason field of warning would be indicated just by the word because that is the default for regular expressions. The user would not need to put percent sign symbols for wild cards. Knowledgeable users could use this facility for more general regular expression queries.

Access LIKE

The Access database supports the standard SQL LIKE operator. However, do check the documentation for your version of the Access product; previous versions might have used symbols other than % and _ for the wildcard.

As was the case with the PHP script, it is important for this application to be able to check if a recordset contains no records. The recordset object does have a method for this purpose: RecordCount. However, this method will not return a valid number unless the recordset has been opened with a third parameter holding a value different from the default value.

    result.Open(sq,Conn, 1)

The third parameter is for the cursor. The default value assumes that the code will read the recordset once from the start until the end. A way of remembering to use this parameter if you need to get a count of the records is to consider that counting the records involves going through the entire recordset. However you think about it, you need to use the open method this way. The code is shown in Table 11.5.

Table 11.5: ASP/JavaScript to Find Warnings with Specified Term

<%@ Language=JavaScript %>

Set the language

<html><head><title>Find shows with certain warnings</title></head><body>

Usual HTML start

<h1>Favorites<br></h1>

Heading

<!— #include file="sopenconn.asp" —>

Include the code for making the connection

<%

Start ASP

var submitted=String(Request ("submitted"));

Extract the hidden input indicating submitted

if (submitted != 'undefined') {

If test to check if the form has been submitted

var problem = String(Request("problem"));

Extract the form input

sq ="SELECT f.title, f.description, w.reason ";

Define the query taking several statements

sq = sq + " from favorites as f, warnings as w where f.favorite_id = w.favorite_id ";

Add to the query

sq = sq + " and w.reason LIKE '" + problem+"'";

Add to the query

Response.Write("Query is "+sq+"<br>");

Output the query for debugging

var result = Server.CreateObject ("ADODB.RecordSet");

Create a variable object of type recordset

result.Open(sq,Conn, 1);

Need cursor setting to be one in order to get a valid RecordCount

if (result.RecordCount==0) { Response. Write("No warnings match: $problem. Use a more general pattern."); } else {

If test to check if there were no records meeting the LIKE condition. If so, output a message. Start else clause

%>

End ASP

<table border='1'>

Straight HTML for table

<tr><td>Titles </td><td>Descriptions </td><td>Reason</td></tr>

Continue with table tags

<%

Restart ASP

while (!result.EOF) {

While loop: will iterate until result recordset is at the end.

Response.Write("\n");

Output line break for the HTML

Response.Write("<tr><td>");

Output table tags

Response.Write(unescape(result.fields. item("title")));

Output the title. Needs to have an escape character removed

Response.Write("</td><td>");

Output table tags

Response.Write(unescape(result.fields. item("description")));

Output the description

Response.Write("</td><td>");

Output table tags

Response.Write(unescape(result.fields. item("reason")));

Output the reason field

Response.Write("</td></tr>");

Output table tags

result.move(1);

Advance to the next record in the recordset

}

End the while

Response.Write(" </table>");

Output table close

} // ends else, when rows in recordset

End the else

Conn.Close();

Close the connection

Response.Write("<a href='sfindwarnings. asp'>Try again </a>");

Output a hyperlink to allow the user to try again

}

Close the if clause for the handle of form

else {

Start else clause: need to display form

%>

Close ASP

<h2>Find shows with warnings containing specific problem </h2><br>

Heading

<form action="sfindwarnings.asp">

Form tag indicating the handler script (the name of this script)

Describe problem <input type='text' name='problem'><br>

Input tag for problem

<input type='hidden' name='submitted' value='true'>

Hidden input tag

<input type='submit' value='Find'>

Button

</form>

Close form

<%

Restart ASP

}

Close of else clause for the display of the form

%>

Close ASP

</body></html>

Usual HTML close

The Access database does not have an operator for SQL conditions with the function of MySQL’s regexp. Please note that VBScript does support regexp as an object type for regular expressions, so you might see regexp in ASP/VBScript programs.

It probably would be appropriate to take any user input and surround it with the wildcard percent sign symbols. This would be done in the var statement defining the variable problem:

    var problem = "%" + String(Request("problem"))+"%";

With this manipulation (some would use the term massaging) of the data entered by the user, the script probably would produce the effects intended.




Creating Database Web Applications with PHP and ASP
Creating Database Web Applications with PHP and ASP (Charles River Media Internet & Web Design)
ISBN: 1584502649
EAN: 2147483647
Year: 2005
Pages: 125
Authors: Jeanine Meyer

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net