<<

ICTWEB502

Create dynamic web pages

Learner Guide

© Copyright, 2015 by North Coast TAFEnow

Date last saved: 9 September 2015 by Amanda Walker Version: 1.0 # of Pages = 39

Tersem Rugbir – Content writer and course adviser

TAFEnow Resource Development Team – Instructional and graphic design

Copyright of this material is reserved to the Crown in the right of the State of New South Wales.

Reproduction or transmittal in whole, or in part, other than in accordance with the provisions of the Copyright Act, is prohibited without written authority of North Coast TAFEnow.

Disclaimer: In compiling the information contained within, and accessed through, this document ("Information") DET has used its best endeavours to ensure that the Information is correct and current at the time of publication but takes no responsibility for any error, omission or defect therein. To the extent permitted by law, DET and its employees, agents and consultants exclude all liability for any loss or damage (including indirect, special or consequential loss or damage) arising from the use of, or reliance on, the Information whether or not caused by any negligent act or omission. If any law prohibits the exclusion of such liability, DET limits its liability to the extent permitted by law, to the re-supply of the Information.

Third party sites/links disclaimer: This document may contain contains links to third party sites. DET is not responsible for the condition or the content of those sites as they are not under DET's control. The link(s) are provided solely for your convenience and do not indicate, expressly or impliedly, any endorsement of the site(s) or the products or services provided there. You access those sites and use their products and services solely at your own risk.

Contents

Getting Started ...... i

About this unit ...... i

Elements and performance criteria ...... i

Icon Legends...... ii

Topic 1 – Identify and -side dynamic content ...... 3

Review Technical Requirements ...... 3

Setting Up a Development Server ...... 7

Client-Side Dynamic Content ...... 10

Server-side Dynamic Content ...... 11

Select Appropriate Languages and Technology ...... 15

Sample Answers ...... 18

Topic 2 – Create dynamic content ...... 20

Create pages using appropriate languages ...... 20

Topic 3 - Test dynamic pages ...... 33

Getting Started

About this unit

This unit describes the performance outcomes, skills and knowledge required to produce both server and client-side content.

Welcome to ICTWEB502 Create Dynamic Web Pages. This unit supports the creation of dynamic web pages that include both client and server-side dynamic content with efficient and effective code to meet technical requirements. The characteristic feature of dynamic website is the compartmentalization of the content and design. Its ‘dynamism’ lies in its vibrancy and interactivity, both in the client-side scripting and server-side scripting. In this unit, you will follow the development of a that allows users to view and update a product catalogue with a login facility. This unit assumes that you have some foundation of creating a simple and control structures as well as exposure to using some JavaScript.

The materials in this unit are to be used as a guide to your study. To get the most out of this guide, make use of other resources such as the or fellow students to further your understanding. The internet is a fantastic resource to assist your learning.

Elements and performance criteria

Elements define the essential outcomes of a unit of competency. The Performance Criteria specify the level of performance required to demonstrate achievement of the . They are also called Essential Outcomes.

Follow this link to find the essential outcomes needed to demonstrate competency in this Unit: http://training.gov.au/Training/Details/ICTWEB502

i | Page ICTWEB502_LG_V1 TAFEnow

Icon Legends

Learning Activities Learning activities are the tasks and exercises that assist you in gaining a clear understanding of the content in this workbook. It is important for you to undertake these activities, as they will enhance your learning.

Activities can be used to prepare you for assessments. Refer to the assessments before you commence so that you are aware which activities will assist you in completing your assessments.

Readings (Required and suggested)

The required reading is referred to throughout this Learner Guide. You will need the required text for readings and activities.

The suggested reading is quoted in the Learner Guide, however you do not need a copy of this text to complete the learning. The suggested reading provides supplementary information that may assist you in completing the unit.

Reference A reference will refer you to a piece of information that will assist you with understanding the information in the Learner Guide or required text. References may be in the required text, another textbook on the internet.

ii | Page ICTWEB502_LG_V1 TAFEnow

Topic 1 – Identify client and server- side dynamic content

Review Technical Requirements

Introduction

These notes will serve as an introduction to the concepts. You are encouraged to do further research to fully understand the concepts. Further resources can be found at the end of the notes.

Before you start your design you need to:

> Identify the goals of your website

> Identify your target audience

3 | Page ICTWEB502_LG_V1 TAFEnow

> Create a list of content that will achieve your goals and be of interest to your audience

It is important that you know the network context within which you will be developing the application. Tech Reader architecture suggests that the web application would be ideal and that it will be installed in-house, an important security consideration.

You will need to employ the three layer application architecture (based on client-server architecture) to allow separation between , programming logic and operations. These separations should be observed as far as it is practical given the technology that you are working with.

Dynamic

A is a web page that provides custom content for the user based on the results of a search or some other request. The ‘dynamic’ term is used when referring to interactive Web Pages created for each user. There are two main ways to customise Web Pages and make them more interactive. The two are often used together because they do very different things.

A script is a set of instructions. For Web Pages, they are instructions either to the (client side scripting) or to the server (server side scripting). Scripts provide change to a Web Page. When you visit a web page, sometimes you’ll notice that there are changes each time you visit it (or during a visit). They probably use scripting.

Client-side scripting is generally referring to the class of computer programs on the web that are executed client-side, by the user’s web browser instead of on the . JavaScript is the main client-side for the Web. Client-side scripts are interpreted by the browser. The process with client-side scripting is:

1 The user requests a Web Page from the server

2 The server finds the page and send it to the user

3 The page displayed on the browser with any scripts running during or after display

4 | Page ICTWEB502_LG_V1 TAFEnow

Client-side scripts are often embedded within an HTML or XHTML document but they may also be contained in a separate file, which is referenced by the document(s) that use it. Client- side scripts may also contain instructions for the browser to follow in response to certain user actions, (e.g., clicking a ). Often, these instructions can be followed without further communication with the server.

In summary, client-side scripting is used to make Web Pages change after they arrive at the browser. These scripts rely on the user’s computer. For the Tech Reader scenario, you will need to create the Web-based forms and have JavaScript perform the validation processes which can include selecting and manipulating the HTML elements.

Server-side scripting is generally referring to the class of computer programs on the web that are executed server-side, by changing the on various web pages. Server responses may be determined by various conditions one of which can be data in the posted HTML , the type of browser being used, or a database or server state. PHP is one main technology for server-side scripting.

The server sends pages to the user/ client on request. The process is:

1 The user requests a web Page from the server

2 The script in the page is interpreted by the server creating or changing the page content to suit the user and the occasion and/ or passing data around

3 The page in its final form is sent to the user and then cannot be changed using server-side scripting

The use of HTML forms allows data to be sent to the server and processed. The results may come back as second Web Page. Server-side scripting tends to be used for allowing users to have individual accounts and providing data from . It allows a level of privacy, personalization and provision of information that is very powerful. E-commerce sites all rely heavily on server-side scripting.

5 | Page ICTWEB502_LG_V1 TAFEnow

In summary, server-side handles logging in, personal information and preferences and provides the specific data which the user wants (and allows new data to be stored). For the Tech Reader scenario, you will need to use PHP to interact with the database and MySQL as the relational database.

MySQL is a relational database management system (RDBMS) that runs as a server providing multi-user access to a number of databases. It is a popular choice of database for use in web applications.

Below is a summarized diagram of how client-side and server-side scripting works:

Source: http://www.bogotobogo.com/php/php1.php

Web Site Organisation

When you have a list of the content you would like to include on your site you can then:

> Divide this list into pages

> Draw a chart () of links between pages

> Decide on the folder structure of your website (root folder & image folder)

6 | Page ICTWEB502_LG_V1 TAFEnow

To complete this unit you will need the following:

> A server environment such as Apache.

> A server side scripting language such as PHP.

> A client side scripting language such as JavaScript.

> Web page development such as Dreamweaver, Expression Web or other HTML editor.

> At least 2 different browsers for testing the web pages.

There are some notes below to help you to prepare the technical environment for your web page but this is optional so long as you’re able to upload your web pages and it dynamically uses functions which are required by Tech Reader and is able to be tested through http://localhost, the local IP address and/ or the full URL.

You may request hosting services from TAFE. Just send an to your facilitator.

Setting Up a Development Server

If you wish to develop Internet applications but don’t have your own development server, you will need to upload every modification you make to a server somewhere else on the Web before you can test it.

Another advantage of a development server is that you don’t have to worry about embarrassing errors or security problems while you’re writing and testing, whereas you need to be aware of what people may see or do with your application when it’s on a public website. It’s best to iron everything out while you’re still on a home or small office system, presumably protected by firewalls and other safeguards.

7 | Page ICTWEB502_LG_V1 TAFEnow

What is a WAMP, MAMP or LAMP?

WAMP, MAMP and LAMP are abbreviations for “Windows, Apache, MySQL, and PHP,” “MAC, Apache, MySQL, and PHP” and “Linux, Apache, MySQL, and PHP.” These abbreviations describe a fully functioning setup used for developing dynamic Internet Web Pages.

WAMPs, MAMPs, and LAMPs come in the form of a package that binds the bundled programs together so that you don’t have to install and set them up separately. This means you can simply download and install a single program, and follow a few easy prompts, to get your server up and running in the fastest time with minimal hassle.

During installation, several default settings are created for you. The security configurations of such an installation will not be as tight as on a production Web Server, because it is optimised for local use.

An example will be to install WAMP. For easy installation and setup of a WAMP server, visit http://easyphp.org. To test the installation, try and display the default web page which will have been saved in the server’s root folder. You may enter either http://127.0.0.1/home or http://localhost/home into the address bar of your browser. If all is well, you will see the default EasyPHP home screen.

The step to make your development server fully functional is to create a folder on your hard disk called tag">c:\web and use it as the directory.

If you encounter difficulties, refer to the FAQ. You may also install the alternatives of WAMP:

> XAMPP: http://www.apachefriends.org/en/xampp.html

> WAMPServer: http://wampserver.com/en/

> If you’re using MAC OS, download MAMP: http://mamp.info/en/download.com

> If you’re using LAMP on Linux, download XAMPP for Linux: http://www.apachefriends.org/en/xampp-linux.html

8 | Page ICTWEB502_LG_V1 TAFEnow

Using FTP

To transfer files to and from your Web Server, you will need an FTP program. You can use FileZilla, FireFTP, or Classic FTP for MAC.

Using a Program Editor

Although plain works for editing HTML, PHP and JavaScript, there are some dedicated program editors such as Editra (for MAC and PC), Notepad ++ and so on.

Using an IDE (Integrated Development Environment)

They offer many additional features such as in-editor debugging and program testing and so on. Some examples include phpDesigner IDE. You may also use Dreamweaver (click here to access the Dreamweaver CS6 tutorial).

Apache

> A well-known HTTP Server; also known as a client-server system - includes Web Browsers, FTP clients and server + the DNS

> Part of its feature is to supports plug-in modules for extensibility i.e. Server-side to authenticate schemes with language interfaces such as PHP

> Allows virtual hosting, DBMS-based authentication databases & content negotiation

> Supports password authentication and digital certificate authentication

> Has a built-in & an HTML authorizing tools and supports FTP.

9 | Page ICTWEB502_LG_V1 TAFEnow

Client-Side Dynamic Content

Dynamic HTML (DHTML) uses HTML, CSS and scripts (commonly Javascript) to provide interactive features on your web pages. The following sections will discuss the dynamic features of JavaScript in some detail, but before you can use these more advanced features it is important to ensure you understand the basics of the language such as:

> How to declare variables

> How to assign values to variables

> How to use constants

> How to declare and call functions

> How to write JavaScript expressions

> How to use operators and the maths functions

> How to use string functions

> How to use conditional and loop statements

You will then be able to build on this basic knowledge to create dynamic web applications. Before you move on further, you should do the tutorials at http://www.w3schools.com/js/default.asp

You will also need to familiarise yourself with HTML 5. You should do the tutorials at http://www.w3schools.com/html/html5_intro.asp. Pay special attention to the semantic and form elements.

For Tech Reader, DHTML will be built namely for the validation checks of the form for registration and products ordered. JavaScript will do the following when user submits a form:

> Make sure all the required fields have something in them (no empty fields)

> Email field have a valid email address, as well as the other field data to match the data types

> Give the user the correct message depending on the error they have made i.e. Enter your first name or Enter a valid email address

10 | Page ICTWEB502_LG_V1 TAFEnow

What you’ll need to remember is that, you will use HTML DOM so that JavaScript can access all the elements of an HTML document. To learn more about this, refer to http://www.w3schools.com/js/js_htmldom.asp

LEARNING ACTIVITIES ACTIVITY 1

Let’s look at the simple example of using Functions and Dot Notation for revision. User will need to Click on the ‘Open Popup Window’ link to open the popup first and then click the ‘Close the Popup window’ link to close the popup. Using the window.close method, you will use the reference to a window to close. For example: popup_window = window.open(“”);

.....

Popup_window.close();

Server-side Dynamic Content

PHP ( Preprocessor)

Basically, web client are designed to display pages that they received as reply to request. The server is enhanced using modules to support script languages such as PHP. One of main focus is on server-side scripting. You can access the PHP program output with a web browser, viewing the PHP page through the server. So with PHP, it’s a simple matter to embed dynamic activity in web pages. Using PHP, you have unlimited control over your web server. Whether you need to modify HTML on the fly, process a credit card, add user details to a database, or fetch information from a third party website, you can do it all from within the same PHP files in which the HTML itself resides.

11 | Page ICTWEB502_LG_V1 TAFEnow

The following sections will discuss the dynamic features of PHP in some detail, but before you can use these more advanced features it is important to ensure you understand the basics of the language by going through them at http://www.w3schools.com/php/default.asp. Pay special attention to PHP arrays, functions and objects.

LEARNING ACTIVITIES ACTIVITY 2

We will look at a simple example of Customer Contact Application’s PHP processing script. This script is going to process data submitted to it when the Add new Contact form submit button is clicked. Save the input form as add_contact.htm.

Remember to add this code:

Next, create the php file.

12 | Page ICTWEB502_LG_V1 TAFEnow

Save this as add_contact.php.

Note the following:

1 All PHP code goes within the tags. Any PHP code in a web page is:

> first executed and replaced with HTML before the web page is sent to the

> browser.

2 Notice that HTML code can be embedded in PHP strings.

3 is a built in function that prints out what's passed to the function as its

> first parameter.

4 $_POST contains an associative array of all the data that was submitted from

> the form. To access a form's control value simply type in $_POST["control

> name"] where "control name" is replaced by the actual name of the control.

Now load add_contact.htm and fill in the form such as below and submit:

13 | Page ICTWEB502_LG_V1 TAFEnow

What is the result?

MySQL

PHP is often coupled with MySQL, a relational database server that can store the information and variables the PHP files may use. Together they can create everything from the simplest web site to a full blown business web site, an interactive web forum, or even an online role playing game.

Information stored in a MySQL database hosted on a web server can be accessed from anywhere in the world. Some examples that can utilise MySQL are a web message board or a customer’s shipping status.

PHP and MySQL complement each other. PHP can collect data and MySQL can in turn store the information. PHP can create a shopping cart for your web store, but MySQL can then keep the data in a format PHP can use to create receipts on demand, show current order status, or even suggest other related products.

14 | Page ICTWEB502_LG_V1 TAFEnow

Select Appropriate Languages and Technology

Before embarking on the languages and technology, you need to be certain that you understand control structures. Expressions and control flow in PHP is important and forms the most fundamental part of any programming language.

This unit is developed with the understanding that you have used control structures such as sequence, selection and iteration.

> "Sequence" refers to an ordered execution of statements.

> In "selection" one of a number of statements is executed depending on the state of the program. This is usually expressed with keywords such as ‘if..then..else..endif’, ‘switch’, or ‘case’.

> In "repetition" a statement is executed until the program reaches a certain state, or operations have been applied to every element of a collection. This is usually expressed with keywords such as ‘while’, ‘repeat’, ‘for’ or ‘do..until’.

You may refer to this as when used in PHP codes: http://www.php.net/manual/en/language.control-structures.php

Learning PHP, MySQL and JavaScript explains each technology separately. Now you will combine them, and consider using valuable programming concepts, including objects, XHTML and so on to create your dynamic webpage. This may include the following:

1 Create web pages with PHP and MySQL by integrating forms and other HTML features

2 Use JavaScript, form functions and event handling to access the DOM ()

3 Upload and manipulate data and images, validate user input

Interacting with MySQL makes PHP a far more powerful tool. We will go through some of the most common ways PHP interacts with MySQL. To follow along with what we are doing, you will need to create a database table by executing this command:

15 | Page ICTWEB502_LG_V1 TAFEnow

This will create a table for us to work with, that has friends' names, favourite colours, favourite foods, and pets.

The first thing we need to do in our PHP file is connect to the database. We do that using this code:

You will replace server, username, password, and Database_Name with the information relevant to your site. mysql_error() function is used to test the connection: http://www.w3schools.com/php/func_mysql_error.asp.

Save this and include file to be included in the subsequent PHP files.

Next we will retrieve the information from the database table we created called "friends"

// Collects data from "friends" table $data = mysql_query("SELECT * FROM friends") or die(mysql_error());

16 | Page ICTWEB502_LG_V1 TAFEnow

And we will then temporarily put this information into an array to use:

// puts the "friends" info into the $info array $info = mysql_fetch_array( $data );

Now let's print out the data to see if it worked:

// Print out the contents of the entry Print "Name: ".$info['name'] . " "; Print "Pet: ".$info['pet'] . "
";

However this will only give us the first entry in our database. In order to retrieve all the information, we need to make this a loop. Here is an example:

while($info = mysql_fetch_array( $data )) { Print "Name: ".$info['name'] . " "; Print "Pet: ".$info['pet'] . "
"; }

LEARNING ACTIVITIES ACTIVITY 3

Now you will need to put all those ideas together to create a nicely formatted table.

17 | Page ICTWEB502_LG_V1 TAFEnow

Sample Answers

Activity 1

18 | Page ICTWEB502_LG_V1 TAFEnow

Activity 2

Activity 3

19 | Page ICTWEB502_LG_V1 TAFEnow

Topic 2 – Create dynamic content

Create pages using appropriate languages

Now that you have the architecture to develop and know how the application should be developed, you may proceed to develop the website.

20 | Page ICTWEB502_LG_V1 TAFEnow

Database

This is a sample definition of the table in the database that will store the login and information. All come with a primary key which will uniquely identify each record. To find out more, visit:

> http://www.w3schools.com/sql/sql_create_db.asp

> http://www.w3schools.com/sql/sql_create_table.asp

21 | Page ICTWEB502_LG_V1 TAFEnow

HTML5

HTML5 is the new standard of HTML. Below is a simple HTML5 document:

You may use the HTML 5 skeleton code. Try some sample codes now from an HTML tutorial: http://www.w3schools.com/html/default.asp

Please note that if you’re going to use HTML5, you need to check your browsers for features supported. You may use: The HTML5 test site for this.

22 | Page ICTWEB502_LG_V1 TAFEnow

Terms and Concepts

Components

HTML 5 incorporates HTML + CSS + JS. From the JS perspective, it uses , Web SQL Database, Application and so on. This new HTML standard has new elements, new attributes, Full CSS3 Support, Video and Audio, 2D/ 3D , etc. HTML 5 was designed with better error handling, reduce need for external plugins (i.e. Flash), more markup, being device independent etc. in mind.

Browser Support

HTML 5 is not yet an official standard therefore no browsers have full HTML 5 support. However, all major browsers (, Chrome, , , IE) continue to add new HTML 5 features to the latest versions. You can read more from: http://html5doctor.com/how-to-get- -working-in-ie-and-firefox-2/

Features

HTML 5 has new elements support better handling of today’s Internet use by providing better structure, better form handling, drawing, and media content. The elements categories are semantic/ structural, media (new), canvas (new), new form elements. Go to http://www.w3schools.com/html/html5_form_elements.asp and explore the new Form Elements.

23 | Page ICTWEB502_LG_V1 TAFEnow

Client-side scripting with JavaScript

LEARNING ACTIVITIES ACTIVITY 4

Example: consider designing your Registration form as part of Client-side Validation process practice.

Designing your form:

With the basic knowledge you have of HTML and CSS, how you design your form plays a role in how easy you will be able to identify your form elements. We are going to design a simple user registration form in XHTML. See screen sample below:

For this form, we are using the

element to call the return validate() JavaScript function.

24 | Page ICTWEB502_LG_V1 TAFEnow

In this example, class="required text"/> has been included for the fields. This means that strings, integers and dates have to be in the correct format in order for it to be correctly stored in the database.

With the basic form done, now you may add some on it.

Next is to ensure that the data entered by the user is exactly what is expected. This is the primary reason for form validation. The advantage seen here is that users will have instant feedback concerning their input and will not crash the server-side software if validated. Our checks will cover the following:

> Blank fields – check for blanks

> Type of data entered – Integer or letter or both (alphanumeric)

> Format of data entered – e.g. email address

To check for blanks, a function needs to be created which will go through all the fields in the form to see if they contain any values, and show appropriate error message:

Let’s call this function checkblanks(pform1). pform 1is the parameter which is used as a DOM element to access other elements in the form. Here is an example of how to use it:

function checkblanks(pform1) { if(pform1.username.value=="") { alert("Please enter a user name") pform1.username.focus() return false }

Notice what this piece of code does – checks the value property of username and if it is blank, it provides an alert to the user and gives the username object the focus again.

An equivalent of this code can be found in JavaScript form validation: http://www.w3schools.com/js/js_form_validation.asp

Return false is a way to tell the event to not actually fire. This is an example of what is termed as event handlers. So, if we had an onsubmit event, return false will that the form is not submitted.

25 | Page ICTWEB502_LG_V1 TAFEnow

You can do the same for the password, name and email elements. The example above accesses the form elements by name but you can also access the elements on the form by referring to their IDs.

We will now consider the data type validation.

This piece of code will also check that the correct number of characters is included so we will consider a function to check passwords. Our password should be minimum six characters and maximum eight characters:

function checkpassword(pform1) { var str=pform1.password.value;

//check required fields //password should be minimum 6 chars but not greater than 8

if ((str.length < 6) || (str.length > 8)) { alert("Invalid password length.") pform1.password.focus() return false } }

Notice that the function above first captures the submitted password and stores it in a variable called “srt”? Then it counts the number of characters (using the length()function) in the password to see if the set restrictions are met.

To ensure that the password is not a number, you may use the isNAN() function. NAN stands for Not a Number. The example:

if(!isNaN(str)) { alert="this is not a number"; pform1.password.focus() return false }

Email address verification can be done by using regular expressions. To validate an email address authors simple look for the ‘@’ sign and a dot(.) in a text to make a valid email address. You may consider the example for http://www.w3schools.com/js/js_form_validation.asp.

26 | Page ICTWEB502_LG_V1 TAFEnow

Now, try sending an email to this address: testing.email@myAddress. This will validate true if the above validation logic is used. However, you can remedy this issue using regular expressions pattern matching capabilities.

function checkemail(pform1) { var email = pform1.email.value;

var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA- Z]{2,4}$/;

if(!(validemail.test(email))) { alert("Invalid email address") pform1.email.focus() return false }

So what did we do here? First of all, we captured the value for email that was sent from the form: var email = pform1.email.value;

Then we declare a validemail pattern for the email address:

var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;

To understand the we will divide it into smaller parts, so that it makes sense:

> /^[a-zA-Z0-9._-]+: means that the email address must begin with alpha-numeric characters (both lowercase and uppercase characters are allowed). It may have periods, underscores and hyphens.

> @: there must be a '@' symbol after initial characters.

> [a-zA-Z0-9.-]+: after the '@' sign there must be some alpha-numeric characters. It can also contain period ('.') and hyphens('-').

> .: after the second group of characters there must be a period ('.'). This is to separate domain and subdomain names.

> [a-zA-Z]{2,4}$/: lastly, the email address must end with two to four alphabets. Having a-z and A-Z means that both lowercase and uppercase letters are allowed while {2,4} indicates the minimum and maximum number of characters. This will allow domain names with 2, 3 and 4 characters e.g.; au, org, com, net, wxyz).

27 | Page ICTWEB502_LG_V1 TAFEnow

Now that you have some basic understanding of regular expressions, let's continue with the code.

We now need to compare the submitted email address against the "validemail" pattern that we defined earlier:

if(validemail.test(email)){

The "test()" property tries to match the submitted email against the pattern that we submitted. We simply notify the user if the test fails:

} else { err.message="Invalid email"; err.field=pform1.email; }

For further understanding and application, please read http://www.w3schools.com/jsref/jsref_obj_regexp.asp and conduct further research.

For your assignment, it will be sufficient just doing a separate validation code for JavaScript and PHP. Just note that PHP validation is most important because JavaScript is frontend code, therefore can be modified or simply disabled by the user.

You can’t use PHP tags in JavaScript. You can only generate either whole JavaScript code or only some data for it using PHP. The next level will be to learn .

Database-driven Website: Use PHP and MySQL

As you’ve done some work in creating simple php files, we will now incorporate more functionality to meet the requirements of Tech Reader.

For example, you could tell PHP to look in the database for a list of books that you would like to appear on your Web site. Before this, create your products table using PHP and MySQL.

28 | Page ICTWEB502_LG_V1 TAFEnow

In this example, the books would be stored entirely in the database. The advantage of this would be twofold. First, instead of having to write an HTML file for each of your books, you could write a single PHP file designed to fetch any book out of the database and display it. Second, to add a book to your Website would just be a matter of adding the book to the database. The PHP code would take care of the rest by automatically displaying the new book along with the rest when it fetched the list of books from the database.

Let’s run with this example as we look at how data is stored in a database.

LEARNING ACTIVITIES ACTIVITY 5

Now that you can connect to your database, remember to close your connection after all the processes have been done.

Create Tables: in this example, we will print a line to indicate a table has been created.

You will need to save the data on the Product form (s) you’ve created. You will need to take note of the following database functions which can be used in the script. mysql_connect - we have had a look at this previously. mysql_select_db

An example of how to collect data to to MYSQL database:

29 | Page ICTWEB502_LG_V1 TAFEnow

$email=$_POST['email']; $location=$_POST['location']; mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); mysql_select_db("Database_Name") or die(mysql_error()); mysql_query("INSERT INTO `data` VALUES ('$name', '$email', '$location')"); Print "Your information has been successfully added to the database."; ?>

It is time to offer some validation to check if the data entered has duplicates. If there exist any data, provide message to say so.

Remember, it will be good to make Product Name Column a UNIQUE INDEX.

Let’s say you wish to check for Product Name if it exists, you may use the WHERE clause to get only rows with the product name. This is just a sample code:

"SELECT * FROM product_list WHERE pname='".$server- >real_escape_string($pname)."'"

Then check if the query results in selecting any rows (either 0 or 1 row) with

MySQLi_Result::num_rows function createProduct($pname,$pdesc) { $server->connect(DB_HOST,DB_USER,DB_PASS,DB_NAME); $result = $server->query("SELECT * FROM products WHERE pname='".$server- >real_escape_string($pname)."'"); if ($result->num_rows() === 0) { if ($server->query("INSERT INTO products (pname) VALUES ('".$server- >real_escape_string($uname)."'")) { echo "Product added Successfully"; } else { echo "Error while adding Product!"; } } else { echo "Product already exists!"; } }

You want to consider validation for all fields on the form. Try this http://www.w3resource.com/php/form/php-form-validation.php

Now that you can save data to your database, you will need to retrieve data from the database

30 | Page ICTWEB502_LG_V1 TAFEnow

table. mysql_query – will retrieve the information from the database table. E.g. for table products:

Temporarily put this information into an array to use: mysql_fetch_array – will return a row from a recordset as an associative array and/or a numeric array. This function gets a row from the mysql_query() function and returns an array on success, or FALSE on failure or when there are no more rows.

Retrieve all the information by putting it all together using a nicely formatted table.

31 | Page ICTWEB502_LG_V1 TAFEnow

Topic 3 - Test dynamic pages

Having completed the website, testing the prototype is the next stage for the web pages. A website that contains dynamic content can be difficult to test.

This is an important process as all the functionality of the prototype will be identified here. You will use this outcome as part of your buy-off process with the stakeholders and as basis for the new website development.

33 | Page ICTWEB502_LG_V1 TAFEnow

There is the common Code Validation:

> HTML – checking the background coding of the design against the (X)HTML Standard (DOCTYPE declaration) the web pages are using. It also needs to meet standards compliant coding with cross browser compatibility issues addressed (IE, Chrome, Opera, Firefox and Safari).

> Use : http://validator.w3.org/#validate_by_upload

> CSS – coding is checked for errors. The code validators check that the web page style sheet coding is in compliance with CSS standards set by the W3C.

> Alt Attribute – ensure that image has an alt attribute.

JavaScript Code Quality Tool: http://www.jslint.com/ and http://www.javascriptlint.com/

Website Navigation

Link checking

Waiting for an object – check whether a page is fully loaded to make sure that all the needed objects exist.

LEARNING ACTIVITIES ACTIVITY 6

> Use : http://validator.w3.org/#validate_by_upload

> Use: http://jigsaw.w3.org/css-validator/validator.html#validate-by-upload

> Use: http://www.javascriptlint.com/online_lint.php

1 Test prototype website in two different browsers

2 Show two errors and how you managed to resolve them.

34 | Page ICTWEB502_LG_V1 TAFEnow

REFERENCE REFERENCE 1

Other Resources

Web Resources

WAMP Installation

PHP, MySQL and JavaScript

Books

Learning PHP, MySQL, and JavaScript : A Step-by-Step Guide to Creating Dynamic . Author: Robin Nixon, Publisher: O'Reilly Media.

ISBN 10: 0596157134

35 | Page ICTWEB502_LG_V1 TAFEnow