Web-based application development

profilelauren II
ip4_lecture_note_3c.pptx

Web-based application development part 3

1

MINIMIZE USER ERROR WITH UI DESIGN

Sometimes it is useful to change the fields in a form so that only possible values can be selected. For example, in the professor information edit form above, if we were to have a typo in the Department textbox upon submission, the database will have an erroneous entry. To reduce such occurrences, we may purposefully change the user interface so that only allowed values are shown. For example, we can show the list of departments as a combo box. Let’s look at how this can be done.

[see code for formEditProfessorWithComboFromDB.php on the next two pages]

2

FROM EDIT PROFESSOR WITH COMBO FROM DB

Not enough space here for the code (see footnote).

Source Code for formEditProfessorWithComboFromDB.php

<html>

<head><title>Form for Editing Professors using ComboBox to Reduce User Error</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><select name=dept>

<?php

$deptQuery = "SELECT DISTINCT Department FROM Professor ORDER BY Department ASC";

$deptResult = mysql_query($deptQuery, $db);

if ($myDeptRow = mysql_fetch_array($deptResult)) {

do {

$department = $myDeptRow['Department'];

if ($department == $dept) {

print "<option value=\"$department\"selected>$department</option>\n";

} else {

print "<option value=\"$department\">$department</option>\n";

}

} while ($myDeptRow = mysql_fetch_array($deptResult));

}

?>

</select>

</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>

3

...

28 <tr>

29 <td>Department: </td>

30 <td><select name=dept>

31 <?php

32 $deptQuery = "SELECT DISTINCT Department FROM Professor ORDER BY Department ASC";

33 $deptResult = mysql_query($deptQuery, $db);

34

35 if ($myDeptRow = mysql_fetch_array($deptResult)) {

36 do {

37 $department = $myDeptRow['Department'];

38 if ($department == $dept) {

39 print "<option value=\"$department\" selected>$department</option>\n";

40 } else {

41 print "<option value=\"$department\">$department</option>\n";

42 }

43 } while ($myDeptRow = mysql_fetch_array($deptResult));

44 }

45 ?>

46 </select>

47 </td>

48 </tr>

...

EXPLANATION OF THE CODE ABOVE

The above code shows an excerpt from formEditProfessorWithComboFromDB.php. It shows the code which generates the dynamic combo box showing only the current departments in the professor table. The rest of the file is exactly the same as the formEditProfessor.php discussed previously. Here is a step by step explanation.

Line 30. We create the <select> input element (i.e. a drop-down list) and name it dept so that the selected combo option will be send to the processing script (editProfessor.php) as a query string (along with pid and pname).

Line 32. We define a query string ($deptQuery) to find the unique departments in the Professor table (using the SQL keyword DISTINCT). The combo box entries should be sorted alphabetically, so we sort the results in the query statement.

Line 33. The query is run on the database connection and the resultset is saved as $deptResult.

Lines 35-44. We loop through the resultset and the Department value for each row is saved as the variable $department. Note that the variable $dept holds the professor’s current department whereas the variable $department holds possible department values from the Professor table. We check with the if statement in line 38 whether the current $department value is the same as the current professor’s department. If so, we use the option tag with the keyword “selected” as an attribute, otherwise, we just write the option entry without the “selected” keyword. The keyword “selected” in the <option> tag specifies that this entry should be selected by default.

Lines 46. We close the <select> tag and finish the combo box.

To run the script, open your browser to http://web.ics.purdue.edu/~yourID/545-examples/formEditProfessorWithComboFromDB.php?pid=P4710.

4

LINKING EVERYTHING

Suppose you wanted to enable in your report (e.g., the list of professors) the editing and deletion of existing records

P4710 David Jordan Economics Edit Delete

So let’s put everything together.

Recall the listAllProfessors.php report, which ran a simple SELECT query (SELECT ProfessorID, ProfessorName, Department FROM Professor) on the MySQL database and wrote a row for each record using a do .. while loop.

Also, recall the formEditProfessor.php form (or the formEditProfessorWithComboFromDB.php) which created a form with data populated from a record in the database (with a SELECT query). That script required that we pass pid in the query string as a HTTP GET variable.

In the listAllProfessors.php script all we need to do to create a link to the formEditProfessor.php form is to write (in HTML):

<a href=“formEditProfessor.php?pid=XXXX”>Edit</a>

where XXXX is the professorID of the record you would like to edit. Since during the do .. while loop, the script has the $pid as a locally stored variable, it is just a matter of writing the link in PHP:

print “<a href=\“formEditProfessor.php?pid=$pid\”>Edit</a>\n”;

So what would we need to do to create the Delete link?

The new “linked” report is shown in listAllProfessorsWithEditDelete.php on the nexr page.

5

LIST ALL PROFESSOR WITH EDIT DELETE

AGAIN, not enough space for the code here…

Source Code for listAllProfessorWithEditDelete.php

<html>

<head><title>Simple Database Query with Links</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><th>Prof Info</th><th>Delete</th></tr>\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>";

print "<td><a href=\"formEditProfessorWithComboFromDB.php?pid=$pID\">Edit Professor</a></td>";

print "<td><a href=\"kill.php?pid=$pID\">Delete Professor</a></td></tr>\n";

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

print "</table>\n";

} else {

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

}

?>

</body>

</html>

6

(SLIGHTLY) ADVANCED PHP TECHNIQUES

Now we will cover functions (queries and commands) and PHP cookies (so that you can easily create the perception of persistence).

7

PHP - FUCTIONS

Useful for encapsulating code for reuse

Syntax

Defining functions

function func_name([parms, ...]) {

// function body

}

Invoking functions

func_name([parms, ...]); // for commands

$var = func_name([parms, ...]); // for questions

Often it is useful to define a reusable block of code so that it may be invoked at different times or from different php scripts. To define a function in php, use the keyword function (as shown above) and to invoke it just call the function in your main routine.

For example,

<?php

// command example

function printSum($a, $b) {

$sum = $a + $b;

print $sum;

}

// question example

function add($a, $b) {

return $a + $b;

}

printSum(2, 5); // this will output “7”

$c = add(1, 4);

print $c; // this will output “5”

8

PHP – FUNCTIONS

Functions

Can work as a 'command' or a 'question'

Variables within a function are local in scope

Pass the necessary variables as arguments

Refer to global variables using the “global” keyword within the function

Example: function.php

Notes:

Commands do things

Questions return values

Variables are local, so if you try to access a local variable from outside the function, it won’t work.

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

9

FUNCTIONS.PHP

NOT enough space for the code (see footnote).

Source Code for function.php

<html>

<body>

<?php

// this example will show how to use functions (methods) in php

// the syntax for the function is:

// function function_name([parms]) { }

// you can invoke (call) the function by function_name([parms])

$a = $_GET['a'];

$b = $_GET['b'];

$test = isGreaterThan($a, $b);

$sum = add($a, $b);

if ($test) {

print "<p>a is greater than b and the sum is $sum\n";

} else {

print "<p>a is NOT greater than b\n";

}

// which is the same as the following without using an intermediate variable

if (isGreaterThan($a, $b)) {

print "<p>a is greater than b and the sum is " . add($a, $b) . "\n";

} else {

print "<p>a is NOT greater than b\n";

}

function isGreaterThan($first, $second) {

if ($first > $second) {

return TRUE;

} else {

return FALSE;

}

}

function add($first, $second) {

global $a, $b;

$a = 5;

$b = 10;

return $first + $second;

}

// NOTE the scope of the $first and $second variables in the function is local

// so the following will not work as intended

print "<p>the sum of a and b is " . add($a, $b) . "\n";

print "<p>the sum of first and second is " . add($first, $second) . "\n";

?>

</body>

</html>

10

HYPERTEXT TRANSFER PROTOCOL

HTTP Request

HTTP version

Host

Method

URI

Client

HTTP Response

Status Code

Date

Server information

Content-type

Body

Internet

HTTP Request

HTTP Request

HTTP Response

HTTP Response

An HTTP Request is sent from the client (web browser) to the server (web server) and the server returns an HTTP Response. One thing to note is that HTTP is stateless.

The request includes information about the HTTP version, the host (server address), the method (GET or POST), the URI (the requested resource/file on the server) and additional information about the client (e.g., browser type, version etc.).

The response has a status code (1xx for success, 2xx for server error, 3xx for HTTP redirects, 4xx for client errors etc.), the date/time of the response, additional server information, content type (e.g., text/html; text/css; image/x-jpeg; application/x-pdf etc.) which tells the browser what to do with the file given the type, and finally it has the actual body of the response (i.e., the HTML source, the data for images etc.). When the client sends the request, all relevant cookie information is also sent to the server as an HTTP Cookie, and the server may make use of this. Let’s look at cookies as this makes it possible to pass information from page to page and overcome the stateless nature of HTTP.

11

PHP- HTTP COOKIES

Cookies are small files stored at the client

Domain specific

Expiration date

Passed to the server in the header

In PHP,

use setcookie(key, value) to set the cookie

$_COOKIE[key] to get the cookie

Example: setCookie.php on the next page

12

Source Code for setCookie.php

<?php

// I'm going to get the cookie with key "name"

// Notice that at first load, $name will NOT be set even if you "get"

// the cookie right afterwards!

// Also, cookies are part of the header of the HTTP Request/Response

// so setting the cookie has to occur prior to any body content.

setcookie("name", "Superman");

$name = $_COOKIE["name"];

?>

<html>

<body>

The value of the cookie with key "name" is <?php print "\"$name\""; ?>

<p>

If nothing shows then try reloading the page!

</body>

</html>

SET COOKIE

13