Chapter 14. Using PHP with JavaScript

CONTENTS

CONTENTS>>

  •  The PHP4 Scripting Language
  •  Passing Data from JavaScript to PHP
  •  Controlling Multiple PHP Pages with JavaScript
  •  JavaScript Form Preprocessing for PHP
  •  JavaScript, PHP, and MySQL
  •  Summary

The PHP4 Scripting Language

For JavaScript users, PHP is an excellent transition language to server-side scripting. Now in Version 4 (or PHP4), PHP is officially named PHP Hypertext Preprocessor. The language was developed in 1994 by Rasmus Lerdorf as a server language for his "Personal Home Page," so he called it PHP. It is now a program scripting language with many similarities to JavaScript, so you should find it relatively simple to master.

PHP generally runs as a mix of HTML and PHP. PHP files are saved in the web server's root directory with the .php extension. The root directory varies with the setup of your system. If you are using your hosting service account, put your files into the root folder, and use your domain name as the root. (Do not put your PHP files in a cgi-bin directory.) For example, if your domain is www.newriders.com, and you save your PHP program in the root directory, you would enter this to call a PHP program:

http://www.newriders.com/yourProgram.php 

Most designers put in additional directories for different projects to keep everything straight. For learning how to use JavaScript with PHP, you might want to add a directory in your web server root directory named PHP and put all of your PHP programs there. With the added directory, you would now enter this to access your PHP file:

http://www.newriders.com/PHP/yourProgram.php 

The addressing process is identical to that of HTML files, but you have to keep in mind the relative relationship to the web server's root directory.

PHP Container

Like JavaScript, PHP code must be written within a container. PHP has three containers that you can choose from.

Container 1
<?php  script goes here  ?>
Container 2
<?  script goes here  ?>
Container 3
<script language="php">  script goes here  </script>

For this book, I will use Container 1. I like it because the beginning tag clarifies the fact that the script is PHP without a great deal of extra effort. The other two methods work fine, and, if you prefer, you can substitute one of them. (Note that Container 3 looks a lot like a JavaScript container.)

Writing and Testing PHP Script

Use a text editor such as Notepad (Windows) or SimpleText (Macintosh) to write your PHP scripts. If you use Notepad, when you save your file as a text file (text document) with a .php extension, make sure that Notepad doesn't add a .txt extension in addition to your .php extension. Place quotation marks around the name of your file when you save it, and Notepad will add no unwanted .txt extension. To get started, write the following script:

<?php  phpinfo( );  ?> 

Save the file as phpinfo.php in your server root directory or subdirectory. For this example, I've saved my PHP file in a folder (directory) named PHP in my web server's root directory, www.newriders.com. To launch the program, I would type this:

http://www.newriders.com/PHP/phpinfo.php 

Substitute your domain name for www.newriders.com, and substitute your directory name for PHP. If you're using your computer as both a client and server, you would type the following, making the appropriate substitutions for the subdirectory name:

http://localhost/PHP/phpinfo.php 

Figure 14.1 shows what you should see if everything is in the right place and is installed correctly.

Figure 14.1. What you see with a successful test of phpinfo.php.

graphics/14fig01.gif

If you see the page depicted in Figure 14.1 (or one close to it), you have correctly accessed PHP in your web server.

Beginning Formats

In PHP, you will see the echo command frequently in use. The command works something like a print command in Basic. The echo command takes the material to the right of the command and displays it in a web page. Generally, the echo command uses this format:

echo "Text, literals or variables."; 

You can also use the echo command to show the output of functions, as in the following:

$fruit="BANANAS";  echo strtolower($fruit); 

The output would display bananas because the function changes all characters in a string to lower case. Throughout the rest of this chapter, you will see the echo command used often because it is the workhorse command to display information to the user through web pages. However, the echo command can also be used to send data back to the server. (The print statement is also used instead of echo, and if you see a PHP listing with print, it is likely to be the developer's preference over using echo.)

Unlike JavaScript, PHP demands a semicolon at the end of most lines. If you leave a semicolon out of certain PHP lines, the program will not execute. For example, a simple variable definition like this one requires that the variable declaration itself end with a semicolon at the end of the line:

<?php  $fruit="Kiwi Fruit";  ?> 

The semicolon is the instructor terminator for statements. However, as in JavaScript, conditional statements never have semicolons after a curly brace. The following shows where the semicolons go and do not go:

<?php  if ($price => $sale) {       $newPrice = $price - ($price * .1);        }  ?> 

PHP is very unforgiving when it comes to semicolons at the end of a command line, so keep an eye out to make sure that your script contains the semicolons that it needs. When debugging your script, first check to see if your semicolons are where they belong. (Your practice of putting in semicolons in JavaScript should really pay off here.)

Comments

As in JavaScript, comments in your code help you remember what you're doing with the code. I will be using the double forward slash (//), just like in JavaScript. The following shows the correct use of comments in a PHP script:

<?php  $newName = $town . ", " . $state;  //The town and state are joined with a comma between them.  echo $newName;  ?> 

The comment line is another exception to the semicolon requirement. You can write anything in a comment line because, as soon as the parser sees the two slashes, it ignores the entire line. You might also see comments written over several lines that begin with /* and end with */. For example, the following is a multiple-line comment:

/* The following comments are made to help clarify how  multiple line comments can be made in a PHP script */ 
Escape Characters

You will find the escape characters in PHP identical to those in JavaScript. A reverse slash (\) escapes the character's usual function. For example, the following shows how to include quotation marks in a variable:

<?php  $favoriteQuote = "Roosevelt said, /"There is nothing to fear but fear itself./"";  echo $favoriteQuote;  ?> 

When the program is executed, the viewer sees the following on the screen:

Roosevelt said, "There is nothing to fear but fear itself." 

Initially, the only character that you will have to remember to escape is the double quotation mark ("). However, when preparing data for a MySQL database, other characters need to be escaped, such as the single quotation mark (') and the ampersand (&). PHP can handle either character without escaping them, but the database cannot. PHP's addslashes( ) function will help take care of the problem by adding the needed slashes automatically when the PHP script is used to add data to a MySQL database. Another function, stripslashes( ), can then be used to remove the slashes so that they won't cause a parsing problem with PHP.

Variables

Declaring a variable in PHP is not unlike doing so in JavaScript, except that all variables in PHP are preceded by a dollar sign ($), and you don't need the var statement. The following script shows integers, floating-point numbers (doubles), and string literals entered into PHP variables:

<?php  $enrollment = 25;  $itemCost=390.21;  $goodAdvice= "Remember Pearl Bailey.";  echo "<p>$enrollment";  echo "<p>$itemCost";  echo "<p>$goodAdvice";  ?> 

The output of the previous example follows:

25  390.21  Remember Pearl Bailey.

The <p> tag simply places an HTML paragraph between each variable output. For the most part, when dealing with PHP and JavaScript, the formatting is accomplished by placing the output in the appropriate variable. What is viewed on the screen will depend on whether you are placing the output from PHP into a variable that will be placed into a form or used in conjunction with document.write( ) or some other statement that places variable information on the screen.

Operators and Conditional Statements

Most of the operators in JavaScript and PHP are the same. Table 14.1 shows the operators used in PHP.

Table 14.1. PHP Operators

Operator

Use

Format Example

=

Assignment

$inven =832;

+

Addition

$total = $item + $tax + $shipping;

-

Subtraction

$discount = $regPrice - $salePrice;

*

Multiplication

$itemTotal = $item * $units;

/

Division

$distrib = $all / $part;

. (dot)

Concatenation

$location = $city . ", " . $state;

%

Modulus

$remainder = 85 % 6;

==

Equal to (compare)

if ($quarter1 == $quarter2) {

===

Equal to + data type

if($forest === $trees) {

!=

Not equal to

if (999 != $little) {

>

Greater than

if ($elephant > $mouse) {

<

Less than

if ($subTotal < 85) {

>=

Greater than or equal to

if ($counter >= 200) {

<=

Less than or equal to

if (300 <= $fullAmount) {

+=

Compound assign add

$total += 21;

-=

Compound assign subtract

$discount -= (.20 * $item);

.=

Compound concatenation

$areaCode .= $phone

&&

Logical AND

if ($first == 97 && $second <=

$third) {

||

Logical OR

if ($high === 22 || $low == 12){

++

Increment (pre or post)

for ($la=6; $la <=78; ++$la)

Decrement (pre or post)

for ($ls=50; $ls >=12; $ls )

JavaScript concatenates strings using the plus (+) operator, and PHP4 uses the dot (.) operator.

Conditional Statements

The conditional statements in PHP4 are very similar to those in JavaScript but are not identical. PHP4 supports three different statements for branching a script.

The if Statement

PHP4 uses the if statement in the same way as JavaScript. When the condition in parentheses is met, the program executes the next line. If the condition is not met, the code in the next line is ignored. For example, the following code will trigger the echo line:

<?php  $cost=55;  $retail=70;  if ($cost < $retail) {       echo "You can make a profit.";        }  ?>
The else Statement

When you have an alternative to the conditional statement using else, the else clause is initiated automatically when the if condition is not met. The following script shows how this works:

<?php  $designTime=88;  $payment=5500;  if ($payment>5000 && $designTime<80) {       echo "Take the job";        } else {       echo "The schedule is too long.";        }  ?>

Note in the previous script how the logical AND (&&) operator is used in the script. Both PHP4 and JavaScript use the logical operators the same way.

The elseif Statement

The formatting of elseif in PHP4 and JavaScript is slightly different. PHP4 uses the single term, elseif, while JavaScript uses else if as two words. However, the rest of the formatting is similar. The following example illustrates how an elseif statement is set up in PHP4:

<?php  $designTime=88;  $payment=5500;  if ($payment>5000 && $designTime<80) {       echo "Take the job";        }  elseif ($payment>6000 || $designTime<90) { echo "This deal will work";  }else {       echo "We just cannot make this work";  }  ?>

When using elseif statements, remember that you need an if statement before beginning a series of elseif statements, and you need an else statement after the last elseif statement, just like in JavaScript. Conditionals are the decision makers in PHP, as in JavaScript, and when creating a dynamic site, the data from the JavaScript in the HTML front end often must be analyzed in a PHP script.

Loops

PHP has three types of loops, and they are structured very similarly to JavaScript loops.

for Loop

A beginning value, a termination condition, and the counter (index) control the for loop. Increments and decrements in the index counter can come before or after the index variable. If the increments/decrements are before the index variable, the change occurs before the counter is employed, while increments/ decrements after the index variable generate change after the going though the loop.

<?php  for ($counter=0; $counter <100; ++$counter) {       echo $unit . $counter;  }  ?>
while Loop

A statement at the beginning of the while loop stipulates the conditions under which the loop terminates. All loop actions take place between the curly braces and include an incremental or decremental variable.

<?php  $counter=100;  while ($counter >1) { echo $unit . $counter . "<BR>";  //$unit is a variable passed from HTML page using JavaScript$counter ;  }  ?>
do...while Loop

Because the counter is at the bottom of the do...while loop, the loop must be processed at least once. The while loop can be terminated before any statement is executed.

<?php  $counter=12;  do { echo $unit . $counter . "<BR>";  //$unit is a variable passed from HTML page using JavaScript$counter ;  } while ($counter >1);  ?>
Arrays

Arrays work the same in both JavaScript and PHP, and the differences are minor. You will find arrays an important PHP tool to use when pulling data from a database and passing the information to JavaScript. Note the differences between array construction in JavaScript and PHP as well as the several ways that arrays are constructed in PHP:

<?php  $book[0] = "The Odyssey";  $book[1] = "The Iliad";  $book[2] = "The Republic";  $book[3] = "Philosophical Investigations";  $book[4] = "Heaving Romances!";  ?>

Like arrays in other scripting and programming languages, the initial element is the 0 element, and not 1. If you list array elements with only the brackets and no numbers, PHP automatically assigns each element based on order of assignment, beginning with 0.

You can also use the array constructor to build an array. It works very much like JavaScript's constructor. For example, the following is an array of fruit:

<?php  $fruits = array ("peach", "apple", "plum", "orange");  ?>

In referencing the array elements, the first value in the array is a peach and is assigned an element identifier of 0. The others are assigned element numbers sequentially so that orange would be element 3. The following script shows the peach and the plum:

<?php  echo $fruits[0];  echo $fruits[2];  ?>

An excellent array feature of PHP is the capability to set the index. A special array operator, =>, sets the sequence. For example, if you want your $fruits array to begin with 1 instead of 0, you could write this:

<?php  $fruits = array (1 => "peach", "apple", "plum", "orange");  ?>

Now peach is 1, apple is 2, plum is 3, and orange is 4. In addition to renumbering, the => operator can be used to create string-indexed arrays. Sometimes your program will make more sense if you use string identifiers. For instance, an array of officers in an organization might use the position initials to identify each one:

<?php  $AcmeOfficers = array ("COB" => "Ralph Smith", "CEO" => "Carolyn Jones", "CFO" =>  "Marilyn Kanter", "CIO" => "Hillman Tech", "VPO" => "George Ready");  echo $AcmeOfficers[CIO];  ?>

In the example, the echo statement returns Hillman Tech because the string index CIO has been associated with the string literal Hillman Tech in the array. Note that the array index identifier has no quotation marks around it in the line with the echo statement.

Searching for Data with an Array

If you want to find a single element in an array, use a loop. When data are placed into an array using numbered elements, all you need is a loop and a counter, as the following example shows:

<?php  $parts=array("nuts" ,"bolts" ,"screws" ,"washers", "wingnuts");  while ($find != "screws") {       $find = $parts[$counter];        $counter += 1;        }  echo $find;  ?>

Looping through data from a database such as MySQL uses a similar process. If the data from the database is placed into an array, you will find it easy to get what you need using a loop. Often, you can use the same loop concept in a table to create a "built-in" array.

PHP Functions

PHP has built-in functions and user functions, just like JavaScript. Likewise, a number of other functions are built into PHP, and you can find them in the online manual at http://www.php.net. Building your own functions works like JavaScript user functions. For example, the following function brings a first and a last name together:

<?php  function fullName ($lastName,$firstName) {       return $firstName . " " . $lastName;  }  echo fullName("Langley", "Harry");  ?>

At this point, you know enough PHP that you can begin doing something with it in relationship to JavaScript. As you will see, most of the work done by JavaScript is limited, but you can effectively use JavaScript with forms to serve as a data-confirmation tool before sending the data to a PHP script.

Passing Data from JavaScript to PHP

In the role of a confirmation tool, JavaScript can check the content of forms before data is sent to a PHP script. Such a role is important for real-world forms because, if troublesome data are sent to a PHP script, the wrong data could end up in your database.

PHP recognizes data from an HTML form element using the same naming structure, but with the added dollar sign before the variable name. For example, if a form element is named this:

alpha 

in an HTML page, it will be recognized as this in a PHP script:

$alpha 

To see one role of JavaScript in gathering in information, these next two scripts, one an HTML page and the other a PHP script, show how data can originate in

JavaScript and be passed to PHP. First, the JavaScript function simply loads up a hidden form with a value. Note that the JavaScript variable greet is placed into a hidden form named alpha. The variable that is passed to the PHP script is alpha because PHP is getting its variable from a form named alpha. Thus, JavaScript makes a "bank-shot" to the form and then to PHP rather than directly to the PHP script.

getData.html
<html>  <head>  <title>Sending Data to PHP </title>  <script language="JavaScript">  function loadIt( ) {       var greet="Hello from PHP.";        document.storage.alpha.value=greet;        }  </script>  </head>  <body onload="loadIt( )";>  <form name="storage" method=get action="greetings.php":>        <input type=hidden name="alpha" >        <input type=submit>  </form>  </body>  </html>

Save this script as getData.html. It uses the get method to open a PHP page named greetings.php. The PHP page immediately echoes whatever is in a variable named $alpha. As you will see, because $alpha is not declared or defined on the PHP page, its content could be only what has been passed to it from the HTML page. Save the following page as greetings.php, and put it in the root directory or subdirectory in your root directory along with the getData.html page.

greetings.php
<html>  <body>  <?php  echo $alpha;  ?>  </body>  </html>

When you run the getData.html script, press the Submit button to launch the PHP script. Your screen shows the line, "Hello from PHP."

Controlling Multiple PHP Pages with JavaScript

One use of JavaScript is to serve as a controller for PHP pages appearing in an HTML environment. Because PHP replaces a page that it is called from, one plan of action is to use JavaScript to create a number of buttons used to launch different PHP pages within a frameset. JavaScript can reside in the menu page, and PHP is called in the body page of a two-column frameset. At the same time, both the JavaScript page and the PHP page share a common external style sheet. Seven scripts are required for this project: an external CSS file, a frameset page, the menu page using JavaScript, a placeholder page, and three PHP pages demonstrating different features of PHP.

Cascading Style Sheet

Using a color scheme from The Designer's Guide to Color Combinations by Leslie Cabarga (North Light Books, 1999), the first step is to create a palette using the following colors. (All values are in hexadecimal.)

Color A

FFE699

Light tan

Color B

CC994C

Tan

Color C

CC0019

Deep red

Color D

00804C

Dark green

Color E

808080

Gray

Color F

000000

Black

This particular color scheme was selected because it contains black and gray, the colors of the buttons in HTML forms. The following style sheet incorporates the colors used in both the PHP and HTML pages.

controller.css
.bigRed {       color: #cc0019;        background-color: #ffe699;        font-family: verdana;        font-weight: bold;        font-size: 18pt;        }  .midRed { color: #ffe699;  background-color: #cc0019;  font-family: verdana;  font-weight:bold;  font-size: 14pt;  }

Save the CSS style sheet in the same directory as the files for the HTML and PHP pages. All of the pages will employ the same style sheet.

This next HTML page establishes the frameset where the initial HTML pages and eventually the PHP pages will go.

controlSet.html
<html>  <frameset cols="25%,*" border=0>        <frame name="menu" src="jMenu.html" frameborder=0 scrolling=0>        <frame name="display" src="jsD.html" frameborder=0 scrolling=0>  </frameset>  </html>

The left side of the frameset opens with a menu page and a blank HTML page in the right frame. All of the JavaScript controllers are in the menu. A simple function in JavaScript is used to launch any of the PHP pages in the right frame.

jMenu.html
<html>  <head>  <link rel="stylesheet" href="controller.css" type="text/css">  <script language="JavaScript">        function loadPHP(url) {       parent.display.location.href=url;        }  </script>  </head>  <body bgcolor=#00804c>  <table border=0 height=70%>        <tr align=left valign=top>        <td bgcolor="#808080">        <center>              <div class="bigRed">&nbsp; Menu&nbsp;</div>              </center>              <br>              <form><input type=button onClick="loadPHP('alpha.php')" value="Selection 1">              <p><input type=button onClick="loadPHP('beta.php')" value="Selection 2">              <p><input type=button onClick="loadPHP('gamma.php')" value="Selection 3">              </td>        </tr>  </table>  </body>  </html>

The initial page in the right frame is a "dummy" page used to occupy space until one of the PHP pages is launched. Figure 14.2 shows how the initial page appears when the frameset is loaded.

Figure 14.2. The area on the right is reserved for PHP by an initial placeholder page.

graphics/14fig02.gif

jsD.html
<html>  <head> <title>Display Page</title>  <link rel="stylesheet" href="controller.css" type="text/css">  </head>  <body bgcolor=#cc994c>        <div class=midRed> &nbsp PHP Pages Appear Here &nbsp </div>  </body>  </html>

The first PHP page simply displays a message in plain text. However, it does load the same style sheet as the two previous HTML pages.

alpha.php
<html>  <head> <title>Control Menu</title>  <link rel="stylesheet" href="controller.css" type="text/css">  </head>  <body bgcolor=#808080>  <center>  <?php        echo "This is plain text.";  ?>  </center>  </body>  </html>

The second PHP page responds with a text message using one of the style sheet classes (see Figure 14.3).

Figure 14.3. A PHP page using the same CSS style sheet as the HTML page appears in the right column.

graphics/14fig03.gif

beta.php
<html>  <head> <title>Control Menu</title>  <link rel="stylesheet" href="controller.css" type="text/css">  </head>  <body bgcolor=#808080>  <center>  <?php        echo "<div class=midRed>&nbsp Here's the other CSS class &nbsp </div>";  ?>  </center>  </body>  </html>

The third PHP page, like the second, responds with a message that indicates yet another of the CSS classes has been employed.

gamma.php
<html>  <head> <title>Control Menu</title>  <link rel="stylesheet" href="controller.css" type="text/css">  </head>  <body bgcolor=#808080>  <center>  <?php      echo "<div class=bigRed>&nbsp CSS Text like the Menu &nbsp</div>";  ?>  </center>  </body>  </html>

The role of JavaScript is to show how PHP pages can be controlled with a JavaScript function and how a common CSS file can provide a common style to front-end and back-end elements of a web site. In the next several sections, you will see how to check and send data from an HTML page to a PHP page using JavaScript for data verification.

JavaScript Form Preprocessing for PHP

Now that the concept of JavaScript's role with PHP is clear, it is time to do something more practical with JavaScript and PHP. This next set of scripts uses JavaScript as a preprocessor to make sure that a comment form being sent has all of the forms filled out and that the user remembers to include an "@" sign in her email address. The JavaScript also shows how to combine two functions into a single function that performs two tasks.

Before starting, you need to know a PHP function not yet discussed. The function mail(e,s,m,h) has four arguments:

  • e Email address

  • s Subject

  • m Message

  • h Header

Each of the arguments can be set as variables or strings in quotation marks. For example, this line would fire off an email to joe@fuzz.com with the other variables' contents going into the subject window, delivering a message, and creating a header:

mail("joe@fuzz.com",$subject,$talk,$whoMe); 

To get started, I selected a French color scheme from Leslie Cabarga's international set of colors in The Designer's Guide to Global Color Combinations (North Light Books, 2001).

Color A

b3cfcc

Gray

Color B

6e9282

Gray-green

Color C

cc0019

Deep red

Color D

f2ede0

Cream

Color E

a44c3a

Terra cotta

Color F

000000

Black

In selecting the colors, I wanted to include a gray and black so that the color scheme would not clash with the form buttons.

mailer.css
.labelText { font-family: verdana;  font-size:11pt;  font-weight:bold;  color:#6e9282;  }  .headerText { font-family: verdana;  font-size:18pt;  color:#c0baae;  font-weight:bolder;  background-color:#a44c3a;  }  body { background-color:#f2ede0;  }

When you have your style sheet created and stored out of the way, you are ready for the main JavaScript page. The following script checks what a user has placed into a form; if a problem is found, an alert message informs the user.

mailForm.html
<html>  <head>  <link rel="stylesheet" href="mailer.css" type="text/css">  <Title>Mail Form</title>  <script language="JavaScript">  //See if any of the document form elements are blank.  function checkBlank() {       var flag=0;        var count;        for (count=0;count<3;count++) {       if (document.mailme.elements[count].value=="") {       flag=1;              }        }              if (flag==1) {             alert("Please fill all the forms.");        }  }  //Make sure the @ is in the email address.  function checkAt() {       var correct=0;        var seek;        var alpha=document.mailme.email.value;        var ampFind=new String(alpha);        var beta=ampFind.length;        for (seek=0;seek<beta;seek++) {             if(ampFind.charAt(seek)=="@") {             var correct=1;              }        }              if (correct==0) {             alert("The @ is missing from your email address.");        }  }  //Put the two functions together.  function checkAll() {       checkBlank();        checkAt();  }  </script>  </head>  <body>  <center>  <div class=headerText>  Mail Form  </div>  </center>  <div class=labelText>  <form name="mailme" method =get action="mailer.php">  Please enter your name:&nbsp; &nbsp  <input type="text" name="name" size=24><p>  Please enter your email address: &nbsp; &nbsp  <input type ="text" name="email" size=40><p>  We'd like to hear what you have to say: <br>  <textarea name="comments" rows=10 cols=80></textarea><P>  <input type="button" value="Click to Verify:" onClick="checkAll()">  <input type="submit">  </form>  </div>  </body>  </html>

What's Going On?

The script is a bit long, but it is really quite simple. The first function, checkBlank( ) sets up a loop that examines the first three elements of the mailme form. (The other elements of the form are buttons and have no input data.) checkBlank( ) looks for the empty quotations (""), and if it finds any, it sets a flag variable named flag. The second function, checkAt( ) examines what the user wrote into the email window to make sure that the @ is in place. To do this, the script first placed the contents of the form into a variable named alpha:

var alpha=document.mailme.email.value; 

That variable is then made into a string object in the variable ampFind so that all of the string functions can be used to find the length of the email address and check each character to see if it contains an @ character. If it does, a flag variable named correct is set. In this case, the alert message is sent only if the flag variable is not set.

The last bit of JavaScript combines both forms so that a single click will check for both types of errors. If an error is detected, a warning appears, as shown in Figure 14.4.

Figure 14.4. The JavaScript detects a mistake and sends an alert message to the viewer.

graphics/14fig04.gif

When the viewer sees the error message, she has an opportunity to correct it before submitting the data to a PHP script. Figure 14.5 shows how the corrected page appears before submitting it.

Figure 14.5. When the problem is solved, no error messages appear on the screen and the user may press the Submit Query button.

graphics/14fig05.gif

mailer.php
<html>  <head>  <link rel="stylesheet" href="mailer.css" type="text/css">  </head>  <body>  <?php  $recipient=$email;  $reply="Dear " . $name . ", \n\n";  $reply .= "Your information has been received. Thank you for filling out the form.";  $reply .= " We will have someone go over comments ";  $reply .= "and get back to you by email soon.";  $reply .= "\n\nSincerely, \nSuzy Q. Less \nPublic Relations";  mail($recipient, "Your Comments",$reply);  $bundle=$comments . "\n\n": . $name . "\n\n" . $email;  mail("yourCompany@email.com","Customer",$bundle);  ?>  <p class=headerText>  <?php echo " Thank you, " .$name; ?>  </p>  <p class=labelText>  <?php echo "You will hear from us very soon."; ?>  </p>  </body>  </html>

What's Going On?

All three of the data-entry form elements in the HTML page are passed to the PHP page. The form elements name, email, and comments are received by PHP as $name, $email, and $comments. These are then used in the PHP script to form a reply, address an email, and pass information to the owner of the web site. Hence, you will see two instances of the mail( ) function. The first sends an email to the person who filled out the forms, and the second sends one to the owner of the web site. Figure 14.6 shows the immediate response that the user sees when he submits the form.

Figure 14.6. A reply on the screen indicates that the information has been sent.

graphics/14fig06.gif

Also note how the PHP code is interspersed with the HTML tags. It is extremely important to remember to put in the semicolons after each PHP line, where appropriate. The same information that is used in the email reply is used to place a message on the screen as soon as the data is submitted. The person who clicks the Submit Query button not only gets a reply immediately on the browser that he's viewing, as shown in Figure 14.6, but he also gets an immediate email signed by a public relations representative, shown in Figure 14.7.

Figure 14.7. An immediate email is sent to the viewer.

graphics/14fig07.gif

The web site owner gets all of the information sent by the viewer. It's a barebones letter with the name, email, and comment variables displayed as a message, as shown in Figure 14.8.

Figure 14.8. The email with the viewer's information is sent to an email address determined by the site owner.

graphics/14fig08.gif

JavaScript, PHP, and MySQL

With JavaScript's capability to check data before it is sent to a PHP script, it serves a valuable role in making sure that data sent from an HTML page are the data that you want in a database. When the data are in the database, you can recall them using HTML aided by JavaScript as a front end.

An open source relational database-management system (RDBMS) typically used with PHP is MySQL. MySQL can be downloaded and used for professional database development. While you can use it without charge for learning and most personal uses, a small fee is required for commercial uses. The current version as I write this page is 3.23.37, and you can be assured that it will be upgraded by the time you read this passage. Check http://www.mysql.com for the latest version.

Fundamental MySQL Commands

One way to learn and practice the basic MySQL commands is to put the MySQL sever on your computer. Download the version of MySQL for your operating system from http://www.mysql.com, install it following the installation prompts, and you should be all set to start creating databases and tables in MySQL.

Use the following steps if you're running everything on your Windows PC for the initial setup:

  1. Select Start, Programs, Accessories, MS-DOS Prompt to open a DOS window.

  2. In the DOS window, type cd c:\mysql\bin\ and press Enter. You will see the DOS window with white type and a black background.

  3. Type mysqld --standalone and press Enter. (Be sure that you have a space between mysqld and --).

  4. Enter the MySQL monitor by typing mysql and pressing Enter. If you've successfully entered the monitor, you will see a mysql> prompt. All commands in the MySQL monitor must be terminated with a semicolon.

  5. (See Figure 14.9.)

    Figure 14.9. From the MySQL monitor, you can enter MySQL commands.

    graphics/14fig09.gif

  6. This next step creates a new database user, and you need to do it just right. Look at Figure 14.9, and type in the same code, pressing the Enter key at the end of each line.

  7. Once you have inserted the user, exit the MySQL monitor by typing exit. You should see the C:\mysql\bin> cursor. Now just type in mysql and press Enter.

Making Your Own Databases and Tables

When you are in the MySQL monitor, you should be able to create databases and tables and add records to the tables. To create a database, type in the following:

mysql> CREATE DATABASE javastore; 

The name of the database just created is javastore, and it is seen by issuing a SHOW DATABASES command (see Figure 14.10).

Figure 14.10. All of the databases in MySQL are displayed, including the one just created.

graphics/14fig10.gif

The command displays all the databases established. The databases named mysql and test are established by default. The database javastore is the one just created. Creating new databases with MySQL is quite simple.

To add a table to the database, first issue a USE javastore; command to select the desired database. Next you will create a table that contains all the fields that you will need for a name and address database. You will need the following nine fields:

  • Identity number

  • Last name

  • First name

  • Address

  • City

  • State

  • ZIP code

  • Phone

  • Email

The purpose is to create a table to show the email addresses of a list of people stored in the database. Each field must include a name, a data type, and the length of the field for fixed length types. Table 14.2 lists a sample of some of the data types in MySQL.

Table 14.2. MySQL Column (Field) Types of Data

Data Type

Description

INT(n)

Integer number

FLOAT

Floating point (single precision)

DOUBLE

Floating point (double precision)

DECIMAL(n,dp)

Float stored as string

CHAR(n)

Fixed-length string from 0 to 255

VARCHAR(n)

Variable-length string from 0 to 255

TEXT

Text field from 0 to 65535 bytes

Create a table using the following format:

mysql> CREATE TABLE tabldogname (field1 DATATYPE(N),   field2 DATATYPE(N)  , etc.); 

Because the table used in this example has nine fields, you will need nine unique field names. Other than the first field that will be an integer number (INT) and the state and ZIP code fields that will be fixed-length strings (CHAR), the values will all be variable-length strings (VARCHAR).

To create the table and all of its fields, be sure that javastore (USE javastore) is the selected database, and enter the following in the MySQL monitor:

mysql> CREATE TABLE clientlist (     -> id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY,      -> lname VARCHAR(20),      -> fname VARCHAR(20),      -> address VARCHAR(40),      -> city VARCHAR(30),     -> state CHAR(2),     -> zip CHAR(5),     -> phone VARCHAR(15),     -> email VARCHAR(35)     -> ); 

After you press the Enter key after the last semicolon, you should see the following:

Query OK, 0 rows affected (0.00 sec)     mysql> 

If you get any kind of error, your table will not be created. To check whether your table is actually formed, type in the command SHOW TABLES . The following shows the sequence:

mysql> SHOW TABLES;  +-------------------------+  | Tables_in_javastore     |  +-------------------------+  | clientlist              |  +-------------------------+  1 row in set (0.00 sec) 

To check all the fields in your table, enter the command EXPLAIN clientlist and press Enter. Figure 14.11 shows what you will see if you have entered your data correctly.

Figure 14.11. All of the fields in the database are displayed.

graphics/14fig11.gif

Entering and Retrieving Records

After you have created a database and table, to make it useful you need a way to enter and retrieve records. To insert records into a table, first be sure that the correct database is selected and then use the following format to enter records:

mysql> INSERT INTO tabldogname VALUES('field1', 'field2'); 

The data that makes up field1 and field2 originates in the HTML page, is checked with JavaScript, and then is sent to a PHP file. So, besides entering the data as literals, variables passed from JavaScript/HTML to PHP to MySQL can be used for entering data into MySQL as well. Moreover, you will find doing so much easier than using the MySQL monitor. The following code shows the correct procedure for entering a record and the feedback from the MySQL monitor:

mysql> INSERT INTO clientlist VALUES(     -> null,      -> 'Smith',      -> 'Joe',      -> '123 Maple Street',      -> 'Taft',      -> 'CA',      -> '92012',      -> '619-555-4502',      -> 'josm@hubahuba.com'      -> );  Query OK, 1 row affected (0.05 sec)  mysql (prompt on screen)

The important value entry is the null in the first field. No matter what record you are entering, when you put in null in an AUTO_INCREMENT field, the value for that record is increased by 1. This automatic value in a primary key means that you don't have to keep track of the unique value that each record will have. So, if you have two people named Joe Smith, each will have a unique number in his id field to distinguish him. Also, when using more than one table in a database, the id field will keep your data in the proper relationship. So, if you have all the names in one table and other information about the same person in another, the common id field with AUTO_INCREMENT will help keep your records straight.

To see the record that you put in, you can specify different characteristics of the record. To see all of the fields and all of the records, use the asterisk (*) as a wildcard character. For example, to see all of the records in your table, you would type this:

SELECT * FROM clientlist; 

Figure 14.12 shows what you would see given the information entered in the example.

Figure 14.12. All of the fields and their values are displayed using the wildcard character.

graphics/14fig12.gif

You can also select just portions of the table in any order your want. For example, you could enter this, and you would get only the selected fields in the order that you listed them:

SELECT id,fname,lname,state FROM clientlist; 

Figure 14.13 shows the outcome from the previous command.

Figure 14.13. Only the selected fields are displayed in the order specified in the command.

graphics/14fig13.gif

A third SELECTION command allows you to select both a field and a field value. For example, if you wanted to find a phone number in which the person's first name was Joe, you could enter this:

SELECT phone FROM clientlist WHERE fname="Joe"; 

Experimenting with different MySQL commands helps you understand the PHP commands that put data into and pull data out of a MySQL database. The data originates in an HTML page and is checked by a JavaScript verification routine. Next, the HTML data is sent to a PHP page, where the variables are used to put information into the database or take it out.

PHP and MySQL

PHP contains a number of functions designed to communicate with a MySQL database. A full list of PHP commands associated with MySQL can be found at http://www.php.net/manual/ref.mysql.php, but for the purposes of this introduction, you will need only a few of the PHP-MySQL functions. Table 14.3 lists the ones used in this chapter.

Table 14.3. PHP MySQL Functions

Function

Result

mysql_connect

Establishes a connection to a MySQL server

mysql_query

Send a MySQL query

mysql_result

Gets result data

mysql_num_rows

Returns the number of rows in result

mysql_select_db

Chooses a MySQL database

PHP Connection to MySQL

The first MySQL function in PHP to learn is mysql_connect(). As you can guess from the name, the function establishes a connection between PHP and the database. To make the connection, the mysql_connect() function requires three arguments: server, user, and password. By placing the names of the server, user, and password into variables, it is easier to make sure that you have the names right and also to change the server, user, or password.

PHP uses the die() function to find out whether a connection is made. So, the or die (message) function is often used to help locate connection problems to the different links that must be made to MySQL. Use the following PHP script to test your connection:

<HTML>  <head>  <Title>Test MySQL Connection</title>  </head>  <body bgcolor="orangered">  <center>  <h1>  <?php  $server="localhost";  $user="hotcoder";  $pass="javascript";  $connectMy=mysql_connect($server,$user,$pass) or die("No connection made.");  if ($connectMy) { $reply="Connection confirmed.";  }  echo "$reply";  ?>  </h1>  </center>  </body>  </html>

Save the script in the root directory of your server, or a directory within the root directory, as connectTest.php. I added a subdirectory to my root directory to keep everything clear:

http://localhost/jsphp/connectTest.php

The server name localhost is one that I used on my computer serving as host and client. On a professional hosting service, you would use your domain name as the root directory and whatever subdirectory you use to store your scripts for a given project. In the previous examples using MySQL, I used the database name of javastore and the username of hotcoder with the password javascript. You can use any names that you want as long as you establish them in the MySQL database first. With the connectTest.php script, you should see a big "Connection confirmed" in the middle of your screen if you have established the MySQL database message.

If your connection fails, check the following:

  • Be sure that you have entered your host (server), user, and passwords into MySQL as shown in Figure 14.8, or in your hosting service's MySQL application for setting usernames and passwords. (The hostname is established by the hosting service.)

  • Check to be sure that you have placed the PHP file in the root directory. If the PHP file is in the wrong place, it won't display at all. This has nothing to do with a failed connection to MySQL.

  • Make sure that your Apache server and MySQL monitor are running if you are using your computer as a client and server.

Selecting the Database with PHP

Use the PHP function mysql_select_db(databasename, connection) to select the that database you want to use. The database name is the name that you have given the database on the host. The connection name is the variable where the mysql_connect() data is stored. This example suppresses the automatic feedback to the web page using an "at" sign (@) in front of the database select function. Only the die() function message is displayed with the @ symbol at the beginning of the select database function.

<?php  //Define elements  $server="localhost";              //Host name  $user="hotcoder";          //User name  $pass="javascript";                  //Password  $javastore ="javastore";    //database name  //Connect to MySQL  $connectMy = mysql_connect($server, $user, $pass);  //Choose database  $dataB=@mysql_select_db($javastore,$connectMy) or die ("Database not responding");  if ($dataB) { $reply="Database is selected and ready to go.";  }  echo "$reply";  ?>

When you can connect to MySQL and the desired database, the rest is pretty smooth sailing. You will find that far fewer problems occur when using a hosting service than when attempting to run both the Apache server and MySQL monitor on your own computer.

Inserting Tables into the Database

The same MySQL commands used in the previous section on creating a table now can be used in a PHP script to create a table for the database. The two-step process involves first creating a string with the MySQL commands. Usually, we prefer to use a variable for the table name so that when a different table needs to be inserted, all we need to do is to substitute table names. In the first step, the string with the command elements replicates the same statements and arguments that would be done in the MySQL monitor. Other than the variable name substituted for the actual table name, the script between the quotation marks is exactly what would be written in the MySQL monitor when creating a table. Next, use the mysql_query(query,connect) function to send the command to MySQL. The following script creates a table named dognames in the database named javastore. Substitute your own names for the user, password, database, and table, if you want. If you are using your own hosting service, be sure to use the root names that your hosting service assigns.

<HTML>  <head>  <Title>Make Table</title>  </head>  <body bgcolor="orangered">  <center>  <h1>  <?php  //Define elements  $server="localhost";          //Host name  $user="hotcoder";             //User name  $pass="javascript";                     //Password  $useBase ="javastore";      //database name  $tabName="dognames";     //table name  //Connect to MySQL  $connectMy = mysql_connect($server, $user, $pass);  //Choose database  $dataB=mysql_select_db($useBase,$connectMy);  // MySQL command in variable  $sql = "CREATE TABLE $tabName (dogname varchar(30), breed varchar(20))";  // Effect Command  $result = @mysql_query($sql,$connectMy) or die("Table not created.");  if ($result) { echo "Table has been created.";      }  ?>  </h1>  </center>  </body>  </html>

Save the script as makeTable.php, and launch it from your browser. If you get any result other than "Table has been created," check your script and the names of the different connections.

Inserting Records into a Table Using PHP and JavaScript

To add records, you will need data sent from HTML to a PHP script. As you have seen in previous sections, you can pass data between HTML and PHP by using the GET method in a form. The role of JavaScript is to verify the data. Both the PHP script and the HTML page use the following color palette saved in an external CSS file:

Color A

FFB3E6

Pink light tan

Color B

260000

Dark, dark red

Color C

A65900

Tan

Color D

664066

Gray

Color E

000000

Black

First, create your CSS page and save it in the root directory.

adder.css
h1 { font-size:18pt;  font-family:verdana;  color:#a65900;  background-color:#260000;  font-weight:bold  }  .bodText { font-family: verdana;  font-size:11pt;  font-weight:bold;  color:#ffb3e6;  background-color:black  }  body { background-color: #a65900;  }

Next, create your HTML page with JavaScript providing verification services, but with the main work being done by HTML forms.

recordAdder.html
<HTML>  <head>  <link rel="stylesheet" href="adder.css" type="text/css">  <Title>Record Adder</title>  <script language="JavaScript">  function checkIt() { for(var x=0;x<2;x++) { var checker=document.forms[0].elements[x].value;  if (checker=="") { alert("Please fill in all windows.");                }         }  }  </script>  </head>  <body>  <center>  <h1>&nbsp Add Records &nbsp</h1>  <form name="records" method=get action="newRecord.php">  <span class=bodText>&nbsp Dog's Name: &nbsp</span>  <input type=text name="name">  <br>  <span class=bodText>&nbsp Dog's Breed:&nbsp</span>  <input type=text name="breed"><p>  <input type="button" value="Verify" onClick="checkIt()">  <input type=submit>  </form>  </body>  </html>

The PHP script gets two variables from HTML. One is name and the other is breed, stored in the form element names. The two HTML variables are transformed into $name and $breed in PHP. The $name variable is part of a record that goes into the field dogname; $breed goes into the field breed in a table named dognames. The general MySQL statements are loaded into a variable, $sql. Then, using the mysql_query function, send the data into MySQL as a record.

addRecord.php
<html>  <head>  <link rel="stylesheet" href="adder.css" type="text/css">  <Title>Add new record</title>  </head>  <body>  <?php  //Define elements  $server="localhost";             //Host name  $user="hotcoder";         //User name  $pass="javascript";                 //Password  $dataB ="javastore";   //database name  $ctable="dognames";        //table name  //Connect to MySQL  $connectMy = mysql_connect($server, $user, $pass);  //Choose database  mysql_select_db($dataB,$connectMy);  //Variables from JavaScript become data for MySQL.  $sql="INSERT INTO $ctable (dogname, breed) VALUES('$name','$breed')";  //Use the query function to send record to MySQL.  mysql_query($sql,$connectMy);  $msg=$name . " has been added.";  echo "<span class=bodText>$msg</span>";  ?>  </body>  </html>

Save the PHP file as newRecord.php, and put it in your root directory or a folder in the root directory along with the CSS and HTML pages. Figure 14.14 shows the initial screen. As soon as the Submit Query button is clicked, the data is sent into the database. With more entries by the user, the role of JavaScript verification becomes more important.

Figure 14.14. The Verify button is JavaScript's contribution to the page.

graphics/14fig14.gif

Selecting Records from a Table

Getting records from a MySQL database via PHP and sent to the browser works very much like the routine for recording records, but the order is reversed. The PHP script first makes the connection and selects the database. Then the script queries the MySQL table using the SELECT statement. To get a better understanding of what happens when selecting data from a table, everything on the table is selected using the wildcard asterisk (*) and is stored in a variable. After getting the data, the next set of statements in PHP gets the precise data that you need.

Initially, SELECT * FROM TABLE dognames pulls out all the information in the table and stores it in a variable named $result. Next, the mysql_result() function returns the data in one cell from a result set. The result set is broken down into the row and field. For example, this statement stores the returns of the contents of row 5 (the sixth row because the rows begin with row 0) of the field titled dogname from the result set of the table named dognames stored in $result.

$name=(mysql_result($result,5,"dogname")); 

You can change the row value (5) to anything that you want, as long as your number is from 0 to the number of rows in your table minus 1.

Because the field dogname contains a pooch's name, the variable $name now should contain the name of the dog that you put into the sixth row (row 5) of the table. The PHP script passes the name back to the browser for viewing.

Passing variables from HTML to PHP was demonstrated in the last example, and this next set of scripts uses the same technique. Thus, to get the results from a row in a table in a database, you have to send only a single number from HTML to PHP. To get started, the following color palette has been selected:

Color A

004CB3

Blue

Color B

FFFFE1

Pale, pale yellow

Color C

A6B380

Muddy green

Color D

D95900

Dark tan

Color E

C5FFC0

Pale blue/green

Color F

000000

Black

First, using colors from the palette, create the following CSS file, and save it and the other two files in the root directory or a subdirectory within your root directory.

select.css
.bodyText { font-family:verdana;  color:#004cb3;  background-color: #ffffe1;  font-size:11pt;  font-weight:bold  }  h1 { font-family:verdana;  font-size:18pt;  color:#c5ffc0;  background-color:#d95900  }

Next, you need an HTML page to pass the data from the user to the PHP page. As noted previously, it requires nothing but a number to be passed to find a row. Like in the previous HTML script, the data value is passed through the name of a form element. (See Figure 14.15.) Look for the dn name in the text form element.

Figure 14.15. The number entered in the text window will be sent to the PHP page as a variable.

graphics/14fig15.gif

selectData.html
<html>  <head>  <link rel="stylesheet" href="select.css" type="text/css">  <Title>Add new record</title>  </head>  <body bgcolor=#a6b380>  <center>  <h1>&nbsp Retrieve Data &nbsp</h1>  <form name="eye" method=GET action="getData.php">  <span class=bodyText>&nbsp Please enter a row number: &nbsp </span>  <input type="text" size=2 name="dn">  <input type=submit>  </form>  </body>  </html>

The key in the HTML file, of course, is the form element with the dn variable name that will be used by PHP to find the desired row. Finally, the PHP page will take the dn variable and display the row information shown in the following script.

getData.php
<html>  <head>  <title>Get the Data</title>  <link rel="stylesheet" href="select.css" type="text/css">  </head>  <body bgcolor=#d95900>  <?php  $server="localhost";                     //Host name  $user="hotcoder";            //User name  $pass="javascript";                       //Password  $dataB ="javastore";         //database name  $ctable="dognames";                    //table name  //Connect to MySQL  $connectMy = mysql_connect($server, $user, $pass);  //Select database  mysql_select_db($dataB,$connectMy);  //Query specific table in database.  $result = mysql_query("SELECT * FROM dognames",$connectMy);  //Get method sends variable data 'dn' from HTML to PHP script $dn.  $name=(mysql_result($result,$dn,"dogname"));  //Form variable value remains constant for both fields.  $breed  =(mysql_result($result,$dn ,"breed"));  $msg=$name . " is a " . $breed;  echo "<span class=bodyText>$msg</span>";  ?>  </body>  </html>

Summary

JavaScript's role in working with server-side languages such as PHP is one of preprocessing. Before data is passed to PHP to be placed into a database, the data needs to be examined to find out whether the user entered the text and values correctly. In this way, when the data is passed to PHP and on to a MySQL database, the user is not surprised to find either empty fields or mistakes that require re-entering data.

However, while JavaScript does have a pivotal role in communications with the server-side elements in a script, the data is passed by the form's submit routine. Unfortunately, the submit() function in JavaScript will not set in motion the necessary elements to send data in the HTML page's forms to the PHP script to be processed. However, you can use the submit() function to launch a PHP script where passing variables in not a requirement.

This very short introduction to PHP and JavaScript is meant to illuminate the role of JavaScript as a preprocessor and to show you how to use the basic elements of PHP. If you are interested in doing more with PHP and JavaScript, many excellent books are available, and several sites are dedicated to PHP where you can learn much more.

CONTENTS


JavaScript Design
JavaScript Design
ISBN: 0735711674
EAN: 2147483647
Year: 2001
Pages: 25

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