Web-based application development

profilelauren II
ip4_lecture_notes__2b.pptx

WEB-BASED APPLICATION DEVELOPMET PART 2

Notes: Server-side scripting refers to a web server technology in which a user’s request is processed at the web server to dynamically generate HTML pages which are sent to the user’s web browser for presentation. Conversely, client-side scripting refers to web technology where an HTML page embeds code (e.g., JavaScript) that is processed by the web browser (i.e. the client).

Notes: Copy the examples into your W: drive under your www folder and use the same URL convention to open them in a web browser. If you put the example files into a sub-directory within the www directory, your URL should reflect that. For example, if you extract the example files to a sub-directory named “545-examples” the URL you should use is http://web.ics.purdue.edu/~yourID/545-examples/example1.html. Obviously you should change yourID for your career account username and example1.html with whatever file you are trying to access.

SERVER-SIDE SCRIPTING AND PHP

While it is (relatively) easy to create HTML pages, the basic HTML language only allows us to create static pages. HTML pages are “static” in the sense that the content of the HTML document will not change as long as the source code is not changed. This property of HTML makes it not well suited for large websites. For example, an online retailer dealing with 100,000 products would require at least 100,000 HTML pages for each of the products and if the retailer decided to reduce the price for a number of products, then each product page needs to be individually edited!

This is where dynamic HTML comes into play. With server-side scripting languages (e.g., ASP or ASP.net for Microsoft IIS, CGI using Perl or Java Server Pages or PHP as modules for the Apache Web Server) it is possible to create a script (i.e., a program) that lets you dynamically display content based on the users’ HTTP requests. Given the availability, we will focus on the PHP language in this tutorial. Most of the other languages for server-side scripting follow similar conventions albeit with different syntax. Hence, if you understand the basic concept of server-side scripting using PHP, it will be relatively easy to apply those concepts to other technologies and languages. Full documentation of the PHP language can be found at http://www.php.net/.

Notes: The PHP installation on web.ics.purdue.edu has some security quirks. You may sometimes get a “HTTP 500 – Internal Server Error”. In such cases, you may need to run the command “webfix” from the shell (login to maven.itap.purdue.edu with your career account ID/password using a SSH client (e.g., SecureCRT) and run “webfix” at the command prompt).

PHP and the concept of server-side scripting

<?php

print "<html>\n";

print "<head><title>Basic PHP - Hello World</title></head>\n";

print "<body>\n";

print "Hello World! This is my first PHP script\n";

print "</body>\n</html>";

?>

The easiest way to think about server-side scripts is to think of them as programs that produce HTML code. In other words, a web application developer writes programs (as server-side scripts) to mimic himself when he is writing HTML code! The program resides on the web server (hence “server”-side) and interprets a user’s HTTP request to create a valid HTML page that is sent back to the client (i.e., the user’s web browser) for rendering.

Let us look at a simple example to understand what this means. The following code in PHP produces a simple “Hello World” page. [see basicPHP.php above]

There are several important things in this example. First, the first and last lines (i.e., <?php and ?>) denote a PHP code block. All statements between these will be interpreted (i.e., run) by the PHP interpreter. Second, we have 5 print statements. The print command just prints to the standard output. Since the standard output in the HTTP environment is fed back to the client, the client (i.e., web browser) will display whatever is printed.

<html>

<head><title>Basic PHP - Hello World</title></head>

<body>

Hello World! This is my first PHP script

</body>

</html>

Note: the \n is just a carriage return in Unix. Since the print statement prints to the standard output, the carriage return is only needed to make the code look better (e.g., for maintenance purposes). If you open the file in a web browser (http://web.ics.purdue.edu/~yourID/basicPHP.php where yourID should be replaced with your career account login), then a simple page with “Hello World! This is my first PHP script” in the main body will appear.

Note: Typically the back-slash (\) character is used as an escape character that is commonly used for unprintable special characters. For example, \t is used for the tab character. Also, you would probably run into problems if you try to print a double quote character since the double quote character delimits the string to be printed in the print command. So if you want to print double quotes in your print statement then you should write \”.

3

PHP blocks

<html>

<?php

print "<head><title>Example 8 – Multiple PHP Code Blocks</title></head>\n";

?>

<body>

<?php

print "Hello World! This is my first PHP script\n";

print "</body>\n";

?>

</html>

A php block

Another php block

You can have multiple PHP code blocks in a HTML file. Simply enclose each PHP code block with <?php and ?> and everything within those statements will be interpreted by the PHP interpreter and everything outside of those blocks will be interpreted as plain HTML. For example (phpBlocks.php):

<html>

<?php

print "<head><title>Multiple PHP Code Blocks</title></head>\n";

?>

<body>

<?php

print "Hello World! This is my first PHP script\n";

print "</body>\n";

?>

</html>

will produce the same result as the previous example. Try it.

4

Processing user input from forms

Method for Sending

GET

POST

Variables in PHP for receiving

$_GET

$_POST

These are hash tables (associative arrays)!

Earlier, we reviewed how to design forms in HTML. This section explains how to process the form data to dynamically produce a resulting HTML page using PHP.

When you fill in the form in forms.html and click on the submit button, the action attribute of the form is tied to “processForm.php. In other words, the form data will be sent to a PHP script called processForm.php.

[see code for processForm.php on the next page]

When form data is sent to a PHP script, the key/value pairs are stored in an associative array (i.e., hash table) called $_GET. In PHP, variables are prefixed with the $ character. Values from an associative array can be retrieved using the key. We define a textbox as follows:

<input type="text" name="name">

The name (key) of the input is “name”. Hence, the value of the “name” input can be accessed with the variable $_GET[‘name’]. The PHP code in processForm.php just gets the values and prints HTML statements from the value. The . (dot) operator in lines 6 through 9 is the string concatenation operator – it appends two strings together. In other words “hello” . “world” give you “helloworld”. The rest of the script should be easy to interpret.

Notes: If the method in the form tag was specified as POST, then the $_POST array would be used instead.

5

Source Code for processForm.php

<html>

<head><title>Processing Data from Form in forms.html</title></head>

<body>

<?php

print "<h1>Form Data You Just Sent</h1>\n";

print "<p>Your name is <b>" . $_GET['name'] . "</b>\n";

print "<p>Your password is <b>" . $_GET['password'] . "</b>\n";

print "<p>Your address is <b>" . $_GET['address'] . "</b>\n";

print "<p>You live in the state of <b>" . $_GET['state'] . "</b>\n";

if ($_GET['plan'] == "on") {

print "<p>You like Project Planning\n";

}

if ($_GET['analysis'] == "on") {

print "<p>You like Systems Analysis\n";

}

if ($_GET['design'] == "on") {

print "<p>You like Systems Design\n";

}

if ($_GET['implement'] == "on") {

print "<p>You like Systems Implementation\n";

}

?>

</body>

</html>

NOTES:

The double equal signs (==) in the php block (lines 11, 14, 17 and 20) are comparison operators. A single equal sign is an assignment operator.

If you want to assign a value to a variable, for instance you want to assign the string “hello world” to the variable $text, or the value stored in variable $copy to a new variable $paste, then you must use the assignment operator =

$text = “hello world”;

$paste = $copy;

If you want to see if the value stored in a variable is some value (either literal or stored in another variable), you’d use the comparison operator ==

if ($text == “hello world”) { ... }

if ($paste = $copy) { ... }

6

Database connectivity using PHP

The PHP language provides many useful functions. One class of functions relates to database connectivity, which makes it extremely easy to connect to a MySQL database to develop database-driven web applications. Database driven dynamic web pages can be typically categorized into two types – 1) reports which just show data and 2) forms which take inputs from the user to update data in a database.

Recall from individual project 3 that the Professor table has three columns named ProfessorID, ProfessorName and Department. An SQL query to retrieve all professors in the database would be:

SELECT ProfessorID, ProfessorName, Department FROM Professor

The following PHP program lists all professors in the database.

[see code for listAllProfessors.php on next page]

To run this PHP script, you need to first edit lines 7 and 8 so that the mysql connection information is correctly specified. Change the username and password in line 7 to your MySQL username and password (the username is your career account username and the password is the password you set for the MySQL account, NOT your career account password). In line 8, use your database name (i.e. your MySQL username).

To prove that this page is dynamic, let us insert a new record in the MySQL database and see if the above script will reflect the changes. Open the MySQL Query Browser (e.g., phpMyAdmin) and run the following SQL statement that inserts a record into the Professor table.

INSERT INTO Professor (ProfessorID, ProfessorName, Department) VALUES ('P6666', 'Hossein Ghasemkhani', 'Management');

Run the PHP script in your browser and check to see if ‘Hossein Ghasemkhani’ is now listed in the HTML output.

NOTE: Some functions used here such as mysql_connect() and mysql_query() are deprecated and will be removed in the future. The good news is that the new functions will be nearly identical (i.e. mysqli_connect(), mysqli_query() ). Since the old ones are still heavily used, I will keep them in this tutorial.

7

Source Code for listAllProfessors.php

<html>

<head><title>Simple Database Query</title></head>

<body>

<h1>All Professors</h1>

<?php

// Database Connection

$db = mysql_connect("mydb.itap.purdue.edu", "USERNAME", "MYSQL_PASSWORD"); // change this!!!

mysql_select_db("USERNAME", $db); // change this also!!!

// SQL query

$query = "SELECT ProfessorID, ProfessorName, Department FROM Professor";

// Resultset object

$result = mysql_query($query, $db);

if ($myrow = mysql_fetch_array($result)) {

print "<table width=100% border=1>\n";

print "<tr><th>ProfessorID</th><th>Professor Name</th><th>Department</th>\n";

do {

// just storing the data for each access later

$pID = $myrow['ProfessorID'];

$pName = $myrow['ProfessorName'];

$dept = $myrow['Department'];

print "<tr><td>$pID</td><td>$pName</td><td>$dept</td>\n";

} while ($myrow = mysql_fetch_array($result));

print "</table>\n";

} else {

print "There are no professors in the database\n";

}

?>

</body>

</html>

The code can be interpreted as follows:

Lines 1 through 4 are just plain HTML code for the header and the top part of the body which is not dynamic.

Line 6 is a comment. 1 line comments in PHP are prefixed with 2 slashes. Multi-line comments can be enclosed in /* comment */ like in Java.

Line 7 creates a database connection object using the function mysql_connect() which takes three parameters – 1) the hostname of the mysql server, 2) the username and 3) the password for the user on the mysql host server. This connection is stored as an object called $db (the name is arbitrary).

Line 8 selects the schema (table space) for that database connection.

Line 11 stores the SQL query into a variable which we call $query.

Line 14 submits the SQL query stored in $query to the database connection $db. The result of this query is stored in the object called $result. The mysql_query() function takes 2 parameters – 1) a query string and 2) a database connection.

Lines 16-31. There is an if /else block here. In line 16, we check whether the result object is empty. The mysql_fetch_array() function which takes a resultset object as an input parameter, fetches the next row from the resultset object. If none exists (i.e., no more rows in the resultset) then the function returns FALSE. This if statement is checking whether there is at least 1 row in the result set. If there is none, we go to the else part of the if/else block (lines 29-31).

Lines 18-19. Now that we know that there is at least one record, we want to set up our table for display. We create a table with 3 columns and we write the header row.

Line 18-27. The do … while loop here loops through the resultset to get the results row by row. Each row that is fetched by mysql_fetch_array() is stored in an associative array (hash) called myrow. The values of the record can be accessed by using the fieldname (or alias in the SQL query) as the key to the myrow associative array. For example, the data in the ProfessorID field can be accessed with $myrow[‘ProfessorID’]. We store the id, name and department of the professor in three variables -- $pID, $pName and $dept (lines 22-24). With these variables we are able to write the row of the table (line 25).

Line 28 ends the <table> tag opened on line 18.

Line 30 is within the else part of the if/else block. From the discussion above, this part is evaluated when there are no records retrieved from the query. So here just print an informative message. Note that this part can be used when there is an error in your SQL statement. If you run an invalid SQL statement (e.g., with typos), then PHP will act as if there are no results from your query. You should be careful to test your SQL statements in MySql or MySQL Query Browser to make sure the SQL statement is valid.

Lines 34-35 just end the body and html tags.

8

Database-enabled forms using PHP

Earlier, we reviewed how to create forms in HTML. Here we will apply that technique to update records in a database. In the previous example we issued an INSERT statement directly to the MySQL database with the MySQL Query Browser to update the database. We now would like to do this in our web-based application. So let us create an input form for inserting new professors.

[see code for formInsertProfessor.html on the next page for the input form]

The HTML code should be straightforward to understand. We have created a form that sends its data to the insertProfessor.php (which we will discuss later). The form data is composed of 3 inputs – professor id (key = pid), professor name (pname) and department (dept).

[see the code for insertProfessor.php for the form processor/controller on the page after the next page]

9

Source Code for formEditProfessor.php

<html>

<head><title>Form for Editing Professors</title></head>

<body>

<?php

// Database Connection

$db = mysql_connect("mydb.itap.purdue.edu", "USERNAME", "MYSQL_PASSWORD"); // change this!!!

mysql_select_db("USERNAME", $db); // change this also!!!

$pid = $_GET['pid'];

$query = "SELECT ProfessorName, Department FROM Professor WHERE ProfessorID = '$pid'";

$result = mysql_query($query, $db);

if ($myrow = mysql_fetch_array($result)) {

$pname = $myrow['ProfessorName'];

$dept = $myrow['Department'];

?>

<form method=GET action="editProfessor.php">

<table width=600 border=1>

<tr>

<td width=150>Professor ID: </td>

<td><?php print $pid; ?><input type=hidden name=pid value="<?php print $pid; ?>"></td>

</tr>

<tr>

<td>Professor Name: </td>

<td><input type=text name=pname value="<?php print $pname; ?>"></td>

</tr>

<tr>

<td>Department</td>

<td><input type=text name=dept value="<?php print $dept; ?>"></td>

</tr>

<tr>

<td colspan=2 align=center><input type=submit value="Click here to submit"></td>

</tr>

</table>

</form>

<?php

} else {

print "error Professor with ProfessorID = $pid not found\n";

}

?>

</body>

</html>

FORM INSERT PROFESSOR

10

Source Code for insertProfessor.php

<html>

<head><title>Inserting Professor from formInsertProfessor.html</title></head>

<body>

<?php

// Database Connection

$db = mysql_connect("mydb.itap.purdue.edu", "USERNAME", "MYSQL_PASSWORD"); // change this!!!

mysql_select_db("USERNAME", $db); // change this also!!!

// HTTP GET VARIABLES (i.e,. form data)

$pid = $_GET['pid'];

$pname = $_GET['pname'];

$dept = $_GET['dept'];

// SQL query

$query = "INSERT INTO Professor (ProfessorID, ProfessorName, Department) VALUES ";

$query = $query . "('$pid', '$pname', '$dept') ";

// Resultset object

if ($result = mysql_query($query, $db)) {

print "Professor ($pname) was successfully inserted\n";

} else {

print "ERROR: Professor ($pname) was NOT successfully inserted\n";

}

?>

</body>

</html>

The line-by-line explanation for insertProfessor.php is as follows:

Lines 1-3 lists the basic (static) HTML header and top of the body.

Lines 6-7 opens a connection to the mysql database on the host mydb.itap.purdue.edu with the username and password and selects the schema.

Lines 10-12 get the form data with the $_GET associative array. We store the professor ID as $pid, the professor’s name as $pname and the professor’s department as $dept.

Lines 15-16 create the SQL INSERT statement using $pid, $pname and $dept.

Lines 19-23 has an if/else block. The mysql_query() function returns a resultset object if successful and FALSE otherwise. So the if statement in line 19 checks if the query was successfully run by the mysql server. Since the SQL statement in question is a data update query (i.e., insert, update or delete), if the return value of mysql_query() is false, then we know that the INSERT was unsuccessful. Hence we print an informative error message in line 22. If the return value is not FALSE (i.e., successful) then we print the message in line 20.

Try inserting new data with the form from formInserttProfessor (http://web.ics.purdue.edu/~yourID/545-examples/formProfessorInput.html), and then check to see if the data was correctly inserted using the listAllProfessors.php (http://web.ics.purdue.edu/~yourID/545-examples/listAllProfessors.php).

Note: you need to replace username, password and schema (lines 6 and 7) to make this work.

11

Dynamic forms using PHP

Sometimes you need to create a form filled with data from a database. For instance, you would like to create a form for editing professor information. In a previous assignment we had professor Scott Moore move from the Management department to the Economics department. In such cases, it is useful to query a database and retrieve (editable) data and display them in a form. We will create a PHP script that queries a database and rather than displaying a table (report) of results, we will populate a form with the data.

[see code for formEditProfessor.php on the next page for the form]

The PHP script formEditProfessor.php should be easy to interpret. To run the script, open your browser: http://web.ics.purdue.edu/~yourID/545-examples/formEditProfessor.php?pid=P4710.

Recall that P4710 is the ProfessorID of ‘David Jordan’. Note that by adding the ?pid=P4710 to the URL you can mimic the submission of a form that sends data (key = pid and value = P4710) to the formEditProfessor.php script via the GET method. By now, you should be able to create a form that sends a pid to this script.

With the pid that is retrieved via the $_GET[‘pid’] variable (line 9), we can write the SQL query to retrieve only the information for ProfessorID = ‘P4710’ (line 11). Since we know that there will only be 1 record (from the assumptions of the business context), we do not need to use a do … while loop to loop through records as we did for the reports. If the query is successful, then we write the form (lines 18-36) by replacing the retrieved values ($pname and $dept) in the value attribute of the input tags. Since we do not want the user to edit the Professor ID (since this may create problems with entity integrity (i.e., primary key) constraints), we only display the $pid and do not make it editable (line 22). However, we need to send this data for processing later. So we include it as a hidden input. When the submit button is clicked, the form data (pid, pname and dept) is sent to editProfessor.php shown below (see action on line 18).

[see code for editProfessor.php on the page after the next for the controller]

The editProfessor.php script is essentially the same as the insertProfessor.php script explained previously with the exception of the SQL query statement. The INSERT statement is replaced by the UPDATE statement. Try editing some professor information and check the results of the editing using the listAllProfessors.php script.

12

Source Code for formEditProfessor.php

<html>

<head><title>Form for Editing Professors</title></head>

<body>

<?php

// Database Connection

$db = mysql_connect("mydb.itap.purdue.edu", "USERNAME", "MYSQL_PASSWORD"); // change this!!!

mysql_select_db("USERNAME", $db); // change this also!!!

$pid = $_GET['pid'];

$query = "SELECT ProfessorName, Department FROM Professor WHERE ProfessorID = '$pid'";

$result = mysql_query($query, $db);

if ($myrow = mysql_fetch_array($result)) {

$pname = $myrow['ProfessorName'];

$dept = $myrow['Department'];

?>

<form method=GET action="editProfessor.php">

<table width=600 border=1>

<tr>

<td width=150>Professor ID: </td>

<td><?php print $pid; ?><input type=hidden name=pid value="<?php print $pid; ?>"></td>

</tr>

<tr>

<td>Professor Name: </td>

<td><input type=text name=pname value="<?php print $pname; ?>"></td>

</tr>

<tr>

<td>Department</td>

<td><input type=text name=dept value="<?php print $dept; ?>"></td>

</tr>

<tr>

<td colspan=2 align=center><input type=submit value="Click here to submit"></td>

</tr>

</table>

</form>

<?php

} else {

print "error Professor with ProfessorID = $pid not found\n";

}

?>

</body>

</html>

FORM EDIT PROFESSOR

13

Source Code for editProfessor.php

<html>

<head><title>Editing Professor from formEditProfessor.php</title></head>

<body>

<?php

// Database Connection

$db = mysql_connect("mydb.itap.purdue.edu", "USERNAME", "MYSQL_PASSWORD"); // change this!!!

mysql_select_db("USERNAME", $db); // change this also!!!

// HTTP GET VARIABLES (i.e,. form data)

$pid = $_GET['pid'];

$pname = $_GET['pname'];

$dept = $_GET['dept'];

// SQL query

$query = "UPDATE Professor SET ProfessorName = '$pname', Department = '$dept' ";

$query = $query . "WHERE ProfessorID = '$pid'";

// Resultset object

if ($result = mysql_query($query, $db)) {

print "Professor ($pname) was successfully edited\n";

} else {

print "ERROR: Professor ($pname) was NOT successfully edited\n";

}

?>

</body>

</html>

EDIT PROFESSOR

14