0% found this document useful (0 votes)
110 views29 pages

Lab 8: Forms - Server-Side WEB1201: Web Fundamentals: Action

This document provides an overview of a lab on handling form data using PHP as the server-side language. The objectives are to create and style a form, send collected data to a server, process the data on the server and store it, and explain different methods of sending data and form elements. Completing prerequisites on HTML, CSS, forms, and page layouts is recommended before attempting this lab. The main tasks involve learning to display data using a web server, writing PHP scripts, connecting to a database server, creating a database and table, writing data to and reading from the database.

Uploaded by

阿符的故事
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
110 views29 pages

Lab 8: Forms - Server-Side WEB1201: Web Fundamentals: Action

This document provides an overview of a lab on handling form data using PHP as the server-side language. The objectives are to create and style a form, send collected data to a server, process the data on the server and store it, and explain different methods of sending data and form elements. Completing prerequisites on HTML, CSS, forms, and page layouts is recommended before attempting this lab. The main tasks involve learning to display data using a web server, writing PHP scripts, connecting to a database server, creating a database and table, writing data to and reading from the database.

Uploaded by

阿符的故事
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Rev 2.7.

2
October, 2020

Lab 8: Forms - Server-side


WEB1201: Web Fundamentals

1 Introduction
This lab aims to help you learn how to handle form data using PHP as the server-side language.
So far, you have learnt how to collect data from the user using forms (See the labs on forms).
But what do you do with this data?

What happens to do the data is determined by the target specified in your form action attribute.
In the previous lab, the target was a HTML file which had no means of handling the incoming
form data. In this lab, you will be exploring using PHP to handle or process the form data.
There are other languages that you can explore for this purpose, for example: Python, Java, C,
C++, C#, etc.

Note

How can I use any language to process the form data? Remember that all data from the
form is sent as a string (i.e. a group of characters). Any language that can process this
string can be used.

When you send the form data to a PHP file, the interpreter will automatically detect this
string, process it (by breaking it up at the & delimiters and changing back any special
characters that were converted before sending) and then saving the received form data in an
array. For PHP, the form values are saved in two pre-defined arrays $_POST and $_GET
(depending on the method specified in the method attribute of the form).

2 Objectives
At the end of this lab, you should be able to:

1. Create a form, style it and send the collected data to a server.


2. Process the data received on the server and store the data.
3. Explain the different methods to send the data to the server.
4. Explain the different elements and attributes used for creating forms and how it affects
the data received in the server.

1
3 Pre-requisites
Before you attempt this lab, it is important that you have completed earlier labs on HTML, CSS,
Page Layouts and Forms. You are expected to understand at least the following topics:

1. HTML terminology: elements, tags, attributes.


2. CSS terminology and knowing how to apply CSS in a variety of ways.
3. The Box Model: understanding padding, margins, etc. and how to apply them.
4. Page layouts: be able to apply a style to your page and form.
5. Forms: be able to create a form with the relevant inputs and be able to style them.

4 Deliverables, timing and additional notes


The estimated time of completion for this lab is approximately four hours. This does not include
the time you will need to answer the questions. You are to compile your work after every lab -
this includes all codes (and comments where necessary), documentation, completed tasks and
answered questions. You will need to submit the work you have produced in this lab.

5 Materials and Equipment


1. A computer with a web browser. A portable browser is needed on the lab computers to
be able to use the Inspector (by pressing F12)
2. A text editor. As usual Visual Studio Code is preferred since it is free and offers syntax
highlighting and code completion.

Note

Have a logbook to write down notes for labs. This will help you revise and reflect on the
work you have done in the lab. The lab is not intended as a typing exercise but one that
requires you to reflect and think about what you have done and learnt.

6 Recap
We collect data from the user using forms, and send the data to a specified location configured
using the action form attribute. The method used, either GET or POST is specified by the
method form attribute.

Everything that happens on the user’s computer is referred to as the “client-side” and everything
that happens on the server is referred to as the “server-side”.

2
7 Overview of today’s lab
As you go through the various tasks in this lab, there is one main thing to remember, everything
you do has to do with: “What you can do with the form data?” We will be exploring mainly
three ways:

1. Display the form data


2. Save the form data
3. Retrieve the form data

However, to be able to do this, you will have to learn a few concepts (in somewhat of a detour).
This is shown in Figure 1.

Start of the lab “Detours”

Learn to display
web page using a
web server

Learn to write a
PHP script

Other tasks that


DISPLAY you will need to
form data learn how to do
Learn to to be able to
CONNECT to a perform the
database SERVER main tasks.

Learn to CREATE
a DATABASE

The main tasks Learn to CREATE


we will be doing a TABLE

SAVE
form data

RETRIEVE
form data

Figure 1: Overview of the lab and side tasks/“detours”.

3
The concepts are:

1. Learn how to write and execute a PHP file.


This will start with Task 1 where you will use the Apache web server to serve your web
site. The Apache web server include a PHP interpreter which will execute your PHP
script. It is the PHP script which will do all the work of processing the form data from
displaying, saving and retrieving the data.
2. Writing your first PHP script (to display values from the form).
This will happen in Task 2 and this is an important task as it will be your introduction to:
(a) writing a PHP script
(b) accessing POST (or GET) data from a form
(c) displaying data from a form
Task 3 shows you a method of dumping or displaying the $_POST or $_GET array
values for troubleshooting purposes.
3. How to create a Database and Table by writing SQL code.
For us to be able to save the data, we need a place to store it. For this, we have chosen to
save it in a table which is in a database on a database server. This starts with:
(a) Learning to login to the database server
(b) Using the login handler to perform actions
(c) Learn the SQL commands to: CREATE a database
Think of it like creating a Microsoft Excel Workbook
(d) Learn the SQL commands to: CREATE a table WITHIN a chosen database
Think of this like creating worksheets within the Excel Workbook
The structure of the database looks like this:
database server
database_1
table_1 of database_1
table_2 of database_1
table_3 of database_1
database_2
table_1 of database_2
table_2 of database_2
database_3
...

4. Writing to the database.


This is the other part of Task 4 - where you will write data to the database.
5. Reading from the database.
This is in Task 5 where you will learn how to retrieve the data from the database and
displaying it.

4
Task 1: Hosting your website on a web server
You are going to turn your computer into a web server and host your website on your local
computer. This task comprises of subtasks, namely:

1. Getting XAMPP and starting your web server (Apache)


2. Testing your XAMPP installation.
3. Copying your website to the root folder location and testing that out.

Note: All the steps for this part of the task is based on the Windows version. If you are using a
different operating system, please search for your own steps.

1. If you are doing this on your computer, you can refer to the video on eLearn to learn how
to get a copy of XAMPP. Get a copy for your particular operating system.
Explanation:
(a) XAMPP is a suite of services (or commonly referred to as a stack) and not just one
program. Using it saves you time and effort from having to download and run each
service individually. Primarily for now, you will need the Apache web server (with
PHP interpreter) and a database (in our case an SQL database).
(b) There are other suites other than XAMPP, e.g. AMPPS and LAMP.
2. If you are doing this on the lab computers, use File Explorer and navigate to c:\xampp.
Press “x” on your keyboard to jump to folders and files starting with “x” or scroll down
to find:
xampp_start.exe
xampp_stop.exe
xampp-control.exe
Explanation:
(a) If you want to start and stop the entire XAMPP suite (i.e. all the modules), you can
use the executable xampp_start.exe and xampp_stop.exe.
(b) If you want to configure each module (or service) or start just a specific one, launch
xampp-control.exe instead.
3. Execute or launch xampp-control.exe.
Depending on whether you are using the portable or installed version or running the
portable version with administrator rights, different services will be made available.
4. For the Apache module (this is your web server), click on “Start” and wait for the module
name to turn green.

5
At this point, you will notice there are values under PID(s) and Port(s). (You can change
the port numbers if there are conflicts on your computer in the Apache configuration)
If you are experiencing issues if you are using your own computer:
(a) Download the installer version (either the portable installer or the full installer). This
should solve most issues. This has to do with permissions to certain folders.
(b) When starting the service, you may be prompted to allow the service through the
firewall. Please allow it, at least for local networks.
5. To test your Apache web server, launch a browser and in the address bar, enter:
(a) 127.0.0.1 (this is a reserved IP address that points back to your computer.), or
(b) Your computer’s unique IP address.
You can find your computer’s unique IP address by launching a “Command Prompt”
(just do a search or press Windows Key + R and type in “cmd”) and at the prompt
type in the command ipconfig. Your computer’s unique IP address is listed under
IPv4 address. In this example, it will be 192.168.1.2. Your computer will most
likely have a different number than the one shown in this example.
1 Ethernet adapter Ethernet:
2
3 Connection-specific DNS Suffix . : mydomain.com
4 Link-local IPv6 Address . . . . . : fe80::b8af:d48f:fcd4:83d2%5
5 IPv4 Address. . . . . . . . . . . : 192.168.1.2
6 Subnet Mask . . . . . . . . . . . : 255.255.255.0
7 Default Gateway . . . . . . . . . : fe80::1:1%5
8 192.168.1.1

6
6. You should be able to see a web page appear.

What you are doing is accessing a web page that is hosted on your local computer. In
short, your local computer is now a web server. In fact, another computer should be able
to access your computer’s web server (provided there is no firewall in the way).
7. In the same c:\xampp folder, look for another folder called \htdocs under the same
path. (You can change the location of this from the Apache configuration). This folder
will contain your entire website. Backup all the contents (if you want to keep them) and
delete everything in here and upload your own website (from your previous lab). Ensure
that your main page is called “index.html”.

Note

If you do NOT want to rename your file or for it to load automatically, include the
filename of the file you want to load after the machine name or IP address.

For example, if the filename of your form is named myform.html, in the address bar
of the browser, you will need to enter http://127.0.0.1/myform.html.

By appending the filename to the end of the computer’s address, you are no longer
accessing a directory but a specific file, negating the need for Apache to search for a
file to serve (if a directory is requested).

The reason why you need to change the filename is because this is one of the default
filenames that Apache will load when you are trying to access a directory (i.e. in this case
the root directory). The files that will be loaded are determined by DirectoryIndex in the

7
Apache httpd.conf (which can be accessed by going to the “config” button for Apache).
Here are the other default filenames which will be loaded.
1 # DirectoryIndex: sets the file that Apache will serve if a directory
2 # is requested.
3 #
4 <IfModule dir_module>
5 DirectoryIndex index.php index.pl index.cgi index.asp \
6 index.shtml index.html index.htm \
7 default.php default.pl default.cgi default.asp \
8 default.shtml default.html default.htm \
9 home.php home.pl home.cgi home.asp \
10 home.shtml home.html home.htm
11 </IfModule>

These are the default filenames for Apache to search for. You can add or remove from this
list or rename your file to one of these filenames. Logically, you would end up naming it
as either index.html, index.htm, index.php, home.html, etc.
8. Test that you can access your website again.
9. Using the steps for getting the IP address, try accessing the website of the people around
you. You should be able to see their website.
10. Make changes to the files for your website and ask those who are accessing your site to
refresh the page.
Note: If you are using VS Code, it is best to open your \htdocs folder using the “Open
folder” command to ensure that you are not updating or modifying the wrong set of files.
11. Try this: Rename your index.html to mymainpage.html. Refresh your webpage. Your
webpage should stop displaying properly. Try to remedy this situation by adding another
line to the DirectoryIndex for your new file i.e. mymainpage.html. Once you have
added the new entry, restart the Apache server by stopping and starting the service or
module again. It should load mymainpage.html.

Question(s) 1

These questions are meant to help you broaden your knowledge and understanding. Do not
copy and paste from a website. Make sure you can explain it in your own words and the
answers must not be ambiguous. Consider what your sources are saying and come to your
own understanding.

1. What are services on a computer? And what do they do for the computer?
2. What do services on your desktop do?

8
3. Explain the port numbers listed for Apache. (You should see two)
4. (Challenge) Explain what PID(s) are.
5. (Challenge) Explain what Port(s) are.
6. What is an IPv4 address?
7. Explain the purpose of the subnet mask?

Task 2: Accessing the form data in PHP


Note

For this task and beyond, it is very important that you:

1. Work within your \htdocs folder.


This is to ensure that whatever files you update will be loaded when you reload
the pages.
2. Ensure that the \htdocs folder you are working with is the one associated with
your Apache web server.
If it is not, your web server will not be serving the correct files. If you are using
the lab computer, the default location for this is in C:\xampp\htdocs.
3. Ensure that you do NOT load any files directly from Windows Explorer (i.e.
DO NOT DOUBLE CLICK or OPEN WITH) but load all files by accessing
your web server (Refer to Task 1).

In this task you will use PHP to access the form data. It will take your form data and display it
back to you (using echo in PHP). To recap, when you send data from a form (using either the
POST or GET method), the data is key-value pair, where the key is the name value given in the
input (or part of a select) and the value is what the user entered. The key-value pairs are sent
like this:
1 name1=firstValue&name2=secondValue&name3=thirdValue

The only difference between POST and GET method is that GET appends these values to
the URL, e.g. http://process.php?name1=firstValue&name2=secondValue&name3=thirdValue.
Note that (regardless of the method used) the values from the form are not sent “as is”. For
example, when the user enters [email protected], the value is sent as: john%40doe.com. The @
symbol is replaced with %40.

When form data is sent to a PHP interpreter, the raw data is processed (i.e. all the delimiters and

9
special characters replaced) and the original form data is restored and placed in an array. The
name of the array depends on the method used, $_GET (for the GET method) and $_POST
(for the POST method). The key of the array corresponds to the name of the input which is
specified using the name attribute of that particular input.

1 <input type="text" id="name" name="user_name">

In this example, the key will be “user_name” which corresponds to the value assigned to the
name attribute of the input.

Note

Before starting on this lab, it is important to use “Open folder” in Visual Studio Code and
open the folder C:\xampp\htdocs. This is to ensure that the files you edit will be in your
web server’s root directory. If you do NOT use the “Open folder” function, when you edit
the files and save it in a different location (other than C:\xampp\htdocs), you will have
to copy the files manually each time after you make changes to the file(s).

1. Launch Visual Studio Code and use the “Open folder” function.
Note:
• All files saved in this lab must be in your web server’s root which by default is in
C:\xampp\htdocs. Opening the folder in VS Code will ensure that the files you
create and edit will be found in your web server’s root.
• If your web server is not on your computer, you will need to transfer or copy your
files to the web server. One way of doing this is to use FTP. On the web server side,
this needs to be enabled and the web server root folder shared.
2. We first need to create a form to capture data. Create a simple form that takes in your first
name, last name and e-mail address. Refer to the lab on HTML forms for this. Save this
as: my_simple_form.html. You can choose to use your form from a previous lab.
Note: The action of this form MUST point to the PHP file you will create later (which
is called actionpage.php or whatever other name you like). The first line of the form
should look like this:

1 <form action="actionpage.php" method="POST">

3. Ensure that each input has a unique name attribute as it will be used by PHP as a key to
enable access to the data value of the specified form field element when you submit the
form. If you do not specify a name attribute, you will not be able to access this value.
Note: You can use the Developer Tools (by pressing F12) to look at the Network portion
and see what is being sent.

10
4. Create this PHP file and save it as: actionpage.php. Ensure that this file is in the \htdocs
folder that is ASSOCIATED with your Apache web server, otherwise, the codes in this
file will not work. Refer to the note at the beginning of this task.
Note:
• Do NOT copy and paste the same code. You will have to type it out.
• Omit the comments (in blue) which start with double forward-slashes (i.e. //)
• Note that the key for single and double quotes is the one beside the “Enter” key for
US style keyboards and not the one shared with the tilde.
• Remember to link this file to your form using the action attribute of your form.
Depending on where you saved your PHP file, you will need to set the correct links
(recall relative and absolute links from Labs 2 and 3).

1 <?php // Marks the beginning of the PHP script


2
3 // Accessing the data from the form and assigning them to variables
4 $firstname = $_POST[’firstname’];
5 $lastname = $_POST[’lastname’];
6 $email = $_POST[’email’];
7
8 // Displaying or printing the values on screen
9 echo ’<h3>Form POST Method</h3>’;
10 echo ’Your name is ’ . $lastname . ’ ’ . $firstname;
11 // There is a space in-between the quotes between the $lastname and
$firstname.
12 exit; // Terminates the PHP script
13
14 ?> //Marks the end of the PHP script

Note:
(a) The ticks that you see in the code are single and double quotation marks and
(b) The PHP file handles the data sent from your HTML form.
(c) A PHP file or script starts and ends with <?php..... ?> (See Line 1 and 14)
(d) A variable in PHP starts with the dollar symbol ($) (See Line 4 and 5).
(e) Variables in PHP do not have to be declared before using and the variable type is
inferred. You can however typecast the variable types when needed.
(f) $_POST (Line 4 and 5) is a special PHP variable called “Superglobals” which are
built-in variables that are always available in all scopes (inside functions). There is
no need to do global $variable; to access them within functions or methods. There
are other superglobals and you can read more about them here.
(g) The data from the form is stored in the $_POST array. In this example the first two

11
lines of code assigns the value to a variable but you can access the values directly.
1 ’Your name is ’ . $_POST[’lastname’] . ’ ’ . $_POST[’firstname’];

(h) The periods (.) are used to concatenate strings. What you are seeing is a “string”
concatenated with another string read from the row with the key “lastname” from
$_POST array and then concatenate with a string which is just a space (blank
space) and then with the first name value from the $_POST array.
(i) You can choose to put this as part of a HTML file but once the file loads you will
receive an error. This is due to Line 10 which is trying to display the value of
variables with no values set (See the isset function). You could check if the values
are set before trying to display them.
(j) The exit on Line 12 ends and terminates the script. This is used without any argu-
ments. The function accepts strings can you can use it to display a string when the
script exits. Read more: here.
5. Create this form and the corresponding PHP file to display the data entered back to the
user.

(a) User’s name (d) Contact details


(b) Date of birth (e) Method of contact
(c) Address/location (f) Your purpose of registration

Note: This just lists the information that you have to collect. You will need to determine
how the form should look like to collect the information, e.g. the user’s name can be
collected using two inputs: last name and first name. Also, ensure that your inputs are of
the correct type.
6. (Challenge) Using the date of birth, calculate the age (in terms of of years, months, and
days) and display that to the user. (Hint: Use PHP’s date and time functions).
7. Modify the codes in both the HTML and PHP from using the POST method to the GET
method. (Hint: There are not a lot of changes)

Question(s) 2

1. What is an array?
2. Discuss the advantages and/or disadvantages in accessing arrays using their
index versus keys.

12
Task 3: Exploring form data in PHP
In this task, you will further explore how data is sent and stored in PHP by running some
experiments. This will be generally broken up into two parts:

1. Displaying the contents of the $_POST or $_GET superglobal arrays. Read more
about arrays here.
2. Discovering what happens when you have a form with TWO inputs having the same
name attribute.

Note that this particular task will not be as guided as the rest and will require you to make
observations to what is happening.

Displaying the contents of an array.


1. Use the PHP function printr or var_dump
2. Record your observation in the file: php_observation.docx or php_observation.txt.

Two form inputs having the same name attribute.


1. Create a form with two inputs which have the same name attribute.
2. Using the Inspector (in Google Chrome), view the data being sent to the web server.
3. Verify the contents of the (appropriate) superglobal by printing the values.

Task 4: Saving the data from the form/Writing to a database


In this task you will use PHP to save the form data into a database (a MySQL database in our
lab but there are other types. You will learn more in Database Fundamentals and Database
Management.). As with writing any data stream (file, network, database, etc.), it is a three (3)
step process.

1. Create a handler to the resource. This typically includes permissions (e.g. read, write,
execute permissions) and to find the resource e.g. a file (which may include creating the
file itself or connecting to a database).
2. Use the handler to carry out your operations (read, write, update, etc.). For databases, we
typically refer to them as CRUD operations (Create, Read, Update, Delete). We can run
multiple operations (or queries) before we close or terminate the handler.
3. Close or terminate the handler.

For this task, we will:

1. look at a typical structure of a database using phpMyAdmin.


2. create a database within the database server,
3. then a table within a specific database, and
4. finally fill the table with data.

13
What does the database server contain? Let us have a look.
1. From your XAMPP Control Panel, start the MySQL service. As usual, once started, the
service label will change to green and a PID and Port number will appear.
2. Go into phpMyAdmin by navigating to http://localhost/phpmyadmin/.
If localhost does not work:
• ensure your Apache module is running (otherwise, phpmyadmin cannot be served).
• change localhost to 127.0.0.1 (for IPv4).
• change localhost to ::1 (for IPv6).
• change localhost to your computer’s unique IP address.
This page will appear.

The purpose of going into phpMyAdmin is to give you a graphical view of the database
layout.
3. On the left are the list of database in your MySQL database server. You can click on each
of the “+” signs to expand the database and look at the tables within them.
4. Click on the database called “test”. This database has been created for you for your
convenience. In other environments, expect to create your own databases.
Note: While you can create a table using phpMyAdmin, you will not use it in this lab as
you will not always have access to it. Also, you will want to create the database using
codes as you will need to recreate your database everytime you come to the lab.
5. Look in the right column and you will see that the “test” database has no tables. A
database can hold several tables which hold the data you want to store.

Instead of using the “test” database, we want to create our own.


This step can be omitted if you choose to use the “test” database instead. You then jump to the
step of creating tables within your database.

6. Here are the codes to connect to your database server and to create a database.
Note: If setting the $password line to an empty quotes "" does not work, try setting the
value to NULL (i.e. $password=NULL). If that fails, try removing the line completely.

14
1 <?php
2 // This code uses MySQLi in a procedural manner to connect to a database.
3 $servername = "127.0.0.1"; // Depends on where your database is located.
In this example, it points back to the local machine
4 $username = "username"; // Username of your database. The default for
MySQL is "root"
5 $password = "password"; // The corresponding password for the username.
The default for MySQL is a blank password. If you have problems using
an empty quote "", try setting the value to NULL (without the quotes).
If that fails, try removing the line completely.
6 // Create connection
7 $handler = mysqli_connect($servername, $username, $password);
8 // Using this method to connect does not connect you to any specific
database but will allow you to create one. Later you will connect to a
specific database.
9
10 // Check connection
11 if (!$handler) {
12 die("Connection failed: " . mysqli_connect_error());
13 } else {
14 echo "Connected successfully";
15 }
16 // To create a database (if you don’t want to use the "test" database) the
command is "CREATE DATABASE <dbname>" where <dbname> is
the name of your database (without the angle brackets)
17 mysqli_query($handler, ’CREATE DATABASE mydb’);
18 ?>

7. You will notice that there is no checking on the success of the function mysqli_query.
To do that, you will need to check the return value of mysqli_query (You can read more
about the mysqli_query function: here). If it returns a TRUE, it is successful. We can
use this in a conditional statement to produce some output.
1 if (mysqli_query($handler, ’CREATE DATABASE mydb’)) {
2 echo "Database created successfully";
3 } else {
4 echo "Error creating database: " . mysqli_error($handler);
5 }

8. Save your complete PHP file as create_db.php in your web server. You can choose to
save it in the root directory or in a subdirectory. Just make sure you know where you
saved it as you will need to access it from the browser’s address bar.

15
(a) If you saved the file in the root.
If you saved in the file in the root of your web server (in this case \htdocs) it is
accessible using http://127.0.0.1/create_db.php.
(b) If you saved the file in another directory.
Add that directory to the URL. For example, if the file is saved in the directory called
db_operations, the file will be accessed using http://127.0.0.1/db_operations/
create_db.php
9. Look at the databases using phpMyAdmin and you should be able to see the new database.

Now lets look at how we can create a table (within a database).


10. To create tables for the database, we first need to connect to it.
Note: As many of the lines of code are similar to that used when creating the database,
comments for these lines will be the same and thus omitted. Refer to the earlier code for
an explanation of what the lines of codes are for.
1 <?php
2 // This code uses MySQLi in a procedural manner to create a table in your
database.
3 $servername = "127.0.0.1";
4 $username = "username"; // Default: "root"
5 $password = "password"; // Leave blank or set to NULL
6 $dbname = "myDatabaseName"; // The name of the database you want to
connect to
7
8 // Create connection TO A SPECIFIC DATABASE (notice the additional
$dbname at the end)
9 $handler = mysqli_connect($servername, $username, $password, $dbname);
10
11 // SQL query to create table
12 $the_query = "CREATE TABLE user_list (
13 id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
14 firstname VARCHAR(30) NOT NULL,
15 lastname VARCHAR(30) NOT NULL,
16 email VARCHAR(50))";
17
18 // Executing the SQL query using the connection handler
19 mysqli_query($handler, $the_query);
20 ?>

Note:
(a) All checks (for successful handler and query execution) in this code has been omit-
ted for clarity sake. Please add that into your code.

16
(b) The code for creating the table only works because it has already connected to a
specific database (See Line 9). Compare this handler to the one used during the
CREATION of the database. When you were creating the database, you connected
to the database server BUT not to a specific database. You will notice that this code
as an additional $dbname at the end when creating the connection handler. This
specifies that the connection is made to a SPECIFIC database (which must exist on
your database server or the connection will fail).
(c) The database to connect to is specified by the variable $dbname (See Line 6). This
line was omitted when you were creating a database as you were not connection to
any specific database but to connect to the server to CREATE a database.
(d) As a table needs to be created INSIDE a database, make sure you are connected to
a database. Otherwise, you will receive an error.
(e) Alternatively, you can specify the database name in the query using the dot notation
(See this link).
1 // “databasename” is the name of the database you want to create the
table in and “user_list” is the name of the table to create
2 $the_query = "CREATE TABLE databasename.user_list....";
3
4 // If you want to use a variable for your database name, the query will
be a concatenated string.
5 $dbname = thenameofmydatabase;
6 $the_query = "CREATE TABLE".$dbname."user_list....";

i. This method of creating a table can be useful if you are already connected to
one database and want to create a table in another rather than creating a new
connection handler to another database.
ii. Tip: You can create multiple handlers and use them as needed. In all our exam-
ples, we have only shown you the creation of a single handler. As handlers are
just references (which are associated to variable names), you can have several.
(f) The checking if the query is successful has been omitted for clarity sake. You can
add that back in your code.
(g) You can think of these as the columns in the table. You can see it in phpMyAdmin.
Details of why it is the way it is beyond the scope of this subject as this is database
related and will be covered in other subjects.
(h) Also, closing of connection wasn’t shown here because after you run one query, you
can continue to run another until you have done all that you want to do with that
database. Once the script it done, the connection is automatically closed anyway.
Closing the connection is more important when your PHP script will continue to do
other things that are not database related.

17
(i) Name this file create_table.php and request for this file from the web server.

Now that we have a place (i.e. a table) to put the data into, let’s look at how we can do it
with some SQL queries.
11. To input data into your database structure your SQL query like this:
1 $sql_query = "INSERT INTO user_list (firstname, lastname, email)
2 VALUES (’John’, ’Doe’,’[email protected]’)";

12. You need to change the VALUES to the values of the variables from your form.
13. Save this file as insert_data.php and link this file to your simple form which only has
the first name, last name and e-mail.
14. Enter at least three different names using the form and check the values from phpMyAd-
min. Later we will look at how you can generate a list or report of the users.
15. Now create another table to accommodate all the data from your earlier created form in
Task 2. Link the form to insert_data.php.

Question(s) 3

1. (Try this in the lab) Can you perform CRUD operations on another database
server rather than your own? Perhaps your friend’s database in the lab?
Hint: To try this out, rather than connecting to your own computer (using ::1,
localhost, 127.0.0.1 or your private IP address), connect to another person’s
computer. If it does not work, try disabling the firewall.
2. Describe what needs to change to allow you to perform CRUD operations on
another database server.
Hint: For a question like this, think about ALL the necessary changes.
3. Describe the various methods to overcome the problem of someone accessing
your database.
Hint: Look at the changes that are required and what needs to be done for
someone to access your database. From there, determine how you can protect
against such access.
4. What are function and return values of functions? What are valid return values?

Task 5: Retrieving data from a database


In this task you will use PHP to retrieve data from the database. The data stream three (3) step
process is used again.

18
1. Create a handler
2. Perform operation(s)
3. Close the handler

Why would you want or need to retrieve data from a database? One reason would be for user
authentication. The others would be to store the resources like images and files for your website
in a database rather than in your folders or directories. (Why do you think this is so?)

1. Start off with creating a handler as you did from above.


2. The difference now is your SQL query will be using a SELECT statement. Generally,
the statement is:
1 // The statement
2 SELECT column_name(s) FROM table_name
3
4 // Performing the query and returning the result into a variable
5 // The return result is an array
6 $result = mysqli_query($handler, sql_statement);

Other examples:
1 // To return all the data from a particular table (i.e. all columns) we use the
universal selector:
2 SELECT * FROM table_name
3
4 // To return certain columns from a table:
5 SELECT lastname, firstname FROM mytable

3. Select rows that match a particular value e.g. if you want to return a particular username
(which should be unique). To do this, extend the statement with WHERE.
1 // The general statement
2 SELECT column_name(s) FROM table_name WHERE conditions
3
4 // return the all columns of users which have the lastname: "Doe"
5 SELECT * FROM mytable WHERE lastname=’Doe’
6 // return just the firstname and e-mail addresses of users which have the
lastname: "Doe"
7 SELECT firstname,email FROM mytable WHERE lastname=’Doe’

Note:
(a) Strings must be in single quotes (See Line 5).
(b) In the examples, the equal to operator is used (See Line 5 and 7). Other operators
include:

19
Sign Operator

= Equal
> Greater than
< Less than
>= Greater than or equal
<= Less than or equal
<> Not equal to
LIKE allows you to select only rows that are “like” what you specify.
The percent sign "%" can be used as a wild card to match any
possible character that might appear before or after the characters
specified.
Here is an example of the use of LIKE
1 // return the all columns of users which have the lastname: Wong,
Tong, Ong
2 SELECT * FROM mytable WHERE lastname LIKE ’%ng%’;

4. After performing the query, the return value is a mysqli_result object which is a result set
identifier. We will fetch a row from the result as an associative array using the function
mysqli_fetch_assoc(). Here is an example by assuming you have this table of data:

id firstname lastname email

1 John Wong [email protected]


2 Bruce Tan [email protected]
3 Jason Ong [email protected]
4 Alex Tan [email protected]
5 Daniel Lim [email protected]

1 // return everyone with the last name "Tan"


2 $query = SELECT * FROM names WHERE lastname=’Tan’;
3 $result_set_identifier = mysqli_query($handler, $query);
4
5 // The return of the mysqli_query() is a mysqli_result object which is a
result set identifier. We saved this identifier in the variable
$result_set_identifier.
6 // To access the results, we will fetch them as an associative array. Accessing
the result set identifier for the first time will return the first row, and
the pointer will automatically increment to point to the next row. Thus,
if you execute this command again, it will return the next result.
7
8 $current_row_result = mysqli_fetch_assoc($result_set_identifier);

20
9 echo "ID: " . $current_row_result["id"] ,"<br>";
10 echo "First name: " . $current_row_result["firstname"] ,"<br>";
11 echo "Last name: " . $current_row_result["lastname"] ,"<br>";
12 echo "E-mail: " . $current_row_result["email"] ,"<br>";

Note:
(a) In this particular example, the results were fetched as an associated array. You can
choose to fetch the data as a different result, e.g. array (using mysqli_fetch_array()),
row (using mysqli_fetch_row()), or an object (using mysqli_fetch_object()).
(b) By running this PHP file, you will only display the first row that matches your query
(your SELECT statement). To display the other rows, you can duplicate the code
from $current_row_result = mysqli_fetch_assoc($result_set_identifier); to the
end, i.e. append this code after itself for as many rows that are returned.
1 $current_row_result = mysqli_fetch_assoc($result_set_identifier);
2 echo "ID: " . $current_row_result["id"] ,"<br>";
3 echo "First name: " . $current_row_result["firstname"] ,"<br>";
4 echo "Last name: " . $current_row_result["lastname"] ,"<br>";
5 echo "E-mail: " . $current_row_result["email"] ,"<br>";

(c) This is not very elegant. Alternatively, you can use a while loop and save all the re-
sults into an array. Declaring an array in PHP using $myarray[] declares an empty
array that can grow dynamically. What you will get with this method is an array of
arrays which looks like this (without the header):

id firstname lastname email

2 Bruce Tan [email protected]


4 Alex Tan [email protected]

1 // This is not the array perse but this code will produce the same array
as looping through the results and saving it into an array.
2
3 $myarray = array (
4 array(2,"Bruce","Tan","[email protected]"),
5 array(4,"Alex","Tan","[email protected]"),
6 );
7
8 // Notice that the id are not strings but integers (refer to how the table
was created) and thus without quotes.
9
10 // And you can access the values using two indices.
11 // Array indexes are counted from zero

21
12 // As there are no specified keys for the subarrays in $myarray, we will
use numbers to refer to them.
13 // But the other values have a key which corresponds to the column (
or attribute) of the database. The key is in text form and thus
must be enclosed in double quotes.
14
15 echo($myarray[0]["firstname"]) // Prints Bruce
16 echo($myarray[1]["firstname"]) // Prints Alex
17 echo($myarray[1]["email"]) // Prints [email protected]
18
19 // If you want to see what the keys are, you can use a var_dump or
print_r on the array variable $myarray. The keys are enclosed in
the square brackets which are exactly what you will need to use to
refer to them.
20
21 print_r($myarray);

5. You will notice that the code does not check for an empty result (e.g. from searching for
something that doesn’t exist). Add code to check for an empty results.
Hint: You can use mysqli_num_rows()
6. Save your PHP file as select_data.php for submission.

Question(s) 4

1. Explain the reasons to why you would put resources in a database rather than a
folder or directory on your web server.
2. Describe the steps that need to be done to allow operations on a database.
3. When retrieving data from a database using the function mysqli_fetch_row(),
what is returned to the calling function?

22
Task 6: Creating a member page
In this task you will add a registration page for your user (or members) and allow them to
retrieve their information on your webpage.

1. Extend or modify the form you created in Task 2 Step 4 to include the following informa-
tion:

(a) First name (g) Address Line 2


(b) Last name (h) Postcode
(c) Date of Birth (i) City
(d) E-mail address (j) Country
(e) Mobile number (k) Preferred contact method (phone,
(f) Address Line 1 e-mail or post)
This should be a radio button.

Note:
(a) Ensure the form uses the correct data type. In a later lab, you will need to include
form sanitization and validation.
(b) Don’t forget to set a value for the radio button as this will be the value returned
using the name. For example:
1 <input type="radio" id="contactChoice1"
2 name="contact" value="email">
3 <label for="contactChoice1">E-mail</label>
4 <input type="radio" id="contactChoice2"
5 name="contact" value="phone">
6 <label for="contactChoice2">Phone</label>
7 <input type="radio" id="contactChoice3"
8 name="contact" value="mail">
9 <label for="contactChoice3">Mail</label>

If the user selects E-mail as the preferred choice, what is sent to the server is con-
tact=email, i.e. name=value. If the user selects Phone, contact=phone will
be sent.
2. Create a table in a database to store the data from the form with these additional columns:
(a) password
This is a special password column that should store the user’s password to allow
them to change their details.
(b) lastmodified
The value in this column will be automatically filled with the current date and time

23
the row (or tuple) was created or modified. You will later use this to show the user
the last time they updated their profile.
3. Create a page to allow the user to register with a password and later login using their
password. You need to read up on Regular Expressions or preg_match for ensuring the
password the user entered meets minimum security requirements.
4. Once login is successful, the user will be redirected to a page that will contain all their
current (or existing) info which is read from the database.
(a) You will have to combine HTML and PHP onto the same page. This allows you to
use variables to create your HTML (making them dynamic pages) which you are not
able to do just with HTML (static pages). Using variables (typically with data read
from a database) allows you to change the content of the webpage. You can read
more about “Static vs Dynamic pages”. To combine HTML and PHP, just write the
HTML code inside the PHP file and save it as a PHP file. The PHP interpreter will
know how to deal with the HTML codes inside the PHP file.
(b) Use the value attribute. The value attribute can be used for a default value in an
input.
(c) Use the checked attribute for the radio box. This will require some logic in PHP to
generate the correct HTML codes.
5. Allow the user to change their info. Use the UPDATE statement to update the info.
1 UPDATE table_name
2 SET column1=value, column2=value2,...
3 WHERE some_column=some_value

The user will need to press a button to submit the updated information unless you have a
script that will automatically submit on change.
6. Before making any changes, show the user what data is to be updated and asking them
for confirmation of the changes to be made. This will be another page showing the user
what has changed and another button to confirm.
7. (Challenge) Alternatively, use a client-side script to show which values have been changed
either by highlighting them or some other method that you find more suitable. We have
yet to cover client-side scripting but you can attempt to do this on your own.
8. If you are wondering how you can update multiple values, try overriding all values. Al-
ternatively, you could perform a comparison of the previous and new values in PHP and
update the database accordingly.

Note: You do not have to submit this task but it is something you might want to try out for
including it in your assignment.

24
8 Using Python for data processing
Recall from the introduction that your action can be directed to other scripts written in other
languages? Well, this section will show you how you can process the form data using Python.

As this section has been included for those of you who are curious or interested in how it is
done, I will not go into details except to say that this method of using CGI (Common Gateway
Interface) has been superseded by other methods and frameworks (e.g. Django for Python)
which are not only faster but safer. Remember, the codes shown here is just an example of
being able to process form data using another language.

8.1 So how does all this work?

We know this. Apache listens on port 80 (for HTTP). When it gets a HTTP request, it parses
the request to find a way to respond. Apache has a LOT of choices for responding. One way to
respond is to use CGI to run a script. Another (common) way to respond is to simply serve a
file (if the request was for a file and if the file is available).

In the case of CGI, Apache prepares an environment and invokes the script through the CGI
protocol. This creates a CGI subprocess (i.e. it is run as a seperate program) which inherits an
OS environment including the socket and stdout. The CGI subprocess writes a response, which
goes back to Apache; Apache sends this response to the browser. (Can you see how many steps
are involved including spawning another process?)

8.2 Now let’s look at some code

We start with coding the form. This is a simple form and you would have produced something
similar in the previous lab. The only difference now is rather than the action attribute pointing
to a PHP file, it points to a Python script.
1 // The action points to a Python script called pythonaction.py which is located in
the cgi-bin directory or folder.
2 // The method you choose does not matter as the Python libraries can support
both GET and POST.
3 <form action="../cgi-bin/pythonaction.py" method="POST">
4
5 // From here on, it is a standard form taking in two text inputs.
6 <div>
7 <label for="fname">First name:</label>
8 <input type="text" id="fname" name="first_name">
9 </div>
10
11 <div>

25
12 <label for="lname">Last name:</label>
13 <input type="text" id="lname" name="last_name">
14 </div>
15
16 <div class="button">
17 <button type="submit">Submit your form</button>
18 </div>
19 </form>

Note:

1. The double periods goes one step up the directory tree. Look at the topic on relative links
from Labs 2 and 3 if you do not understand the double periods before the path to the
script.
2. The Python script is put in the cgi-bin folder as it is the default for the Apache web server
and typically, all CGI scripts are put in this folder for execution. This might be different
on different operating system and as usual, you can configure this folder to somewhere
else based on your web server configuration.

Your Python script should look like this:


1 #!"C:\Program Files\Python37\python.exe"
2 # Import modules for CGI handling
3 import cgi, cgitb
4
5 # Create instance of FieldStorage
6 form = cgi.FieldStorage()
7
8 # Get data from fields
9 first_name = form.getvalue(’first_name’)
10 last_name = form.getvalue(’last_name’)
11
12 print ("Content-Type: text/html\n\n")
13
14 # Here comes the rest of the hypertext document
15 print ("<html>")
16 print ("<head>")
17 print ("<title>My First CGI-Program </title>")
18 print ("<head>")
19 print ("<body>")
20 print ("<h3>Hello " + first_name + ", " + last_name + "</h3>")
21 print ("</body>")
22 print ("</html>")

26
Save this file as: pythonaction.py into the cgi-bin folder. Note:

1. This was tested with Python 3.7. It should work with other versions.
2. You will notice that the print statement is written as a function call. This is because this
was written for Python 3.x.

Load your form, enter the data and the name you entered should be printed after you submit the
form.

9 Summary
This lab was to introduce you to creating your own form. It is expected that at the end of this
lab:

1. You will be able to host your website on a web server.


2. You will be able to collect data from a form and display it to the user.
3. You will be able to save the collected data into a database.
4. You will be able to retrieve and update data in a database.

Submission
In your submission archive, you should have the following files/folders:

1. All the named files in this lab


2. Exported copies of your database table in any importable format (e.g. CSV).
3. Answers to questions in a PDF file

Ensure the following:

1. The file is correctly named and in the correct format. The naming convention is found on
eLearn but for the sake of completeness, for this lab it will be:
<ID>_<labNum>.zip, where:
• <ID> is your student ID, and
• <labNum> is the number of this lab.
2. Do not use any other archive type. The file you submit must be the zip format. If you
are using your laptop and do not have that software, you can download a free zip archive
creator from the 7zip download page. If you are using 7zip, remember to change the
archive format to ZIP. For Mac users, you can use Keka.

The submission link will be found on eLearn. Adhere to the guidelines and instructions on
eLearn.

27
Changelog
• Version: 2.7.2
Date: 19 Oct 2020
1. Updated: Figure 1. Typographical error and change the curly braces from a shaped line
to one without.
2. Updated: Loaded in the latest class file for the lab.

• Version: 2.7.1
Date: 7 Nov 2019
1. Updated: The structure of the lab - the flow of the main tasks and side tasks.
2. Changed: Page layout changed from two side to single.

• Version: 2.7
Date: 1 Nov 2019
1. Rewrote large parts of Task 4 to try to clarify what is happening.

• Version: 2.6
Date: 31 Oct 2019
1. Added more notes to avoid common mistakes made by students.
(a) Failing to load the files using the web server
(b) Failing to put the files (or update the correct files) in the htdocs folder for the web
server to load from.
2. Added more to the introduction to tell the students what they are doing.
3. Added a diagram an a more in-depth explanation of the lab overview.
4. Added another section to demonstrate how another language can be used to process the
form data.
5. Added a note on how to load a file through the web server.
6. Added some questions to the question sections.
7. Fixed some spacing (due to the added content).
8. Fixed some spelling errors.
9. Minor language changes to clarify some parts.

• Version: 2.5
Date: 25 Oct 2019
1. Added some notes to avoid common mistakes made by students.

• Version: 2.4
Date: 24 Oct 2019
1. Corrected some omissions in the task and removed some images.
2. Added some questions to Question 2.

• Version: 2.3

28
Date: 23 Oct 2019
1. Reworded the Objectives
2. Added Pre-requisites

• Version: 2.2
Date: 23 Oct 2019
1. Corrected spelling to Question(s) 2 and added Hints.
2. Added some additional info to Task 4.

• Version: 2.1
Date: 22 Oct 2019
1. Changed the colour of some keywords to make reading easier.
2. Added colours to the code in the labsheet.
3. Rewrote some the explanation for Task 2.
4. Renamed tasks.

29

You might also like