0% found this document useful (0 votes)
268 views

Module For PHP ICT 9

The document provides an introduction to creating an online ordering form using PHP, JavaScript, and SQL. It discusses the importance of algorithms and flowcharts in programming. It begins by defining an algorithm as a set of steps to solve a problem. Key aspects of algorithms like correctness, readability, efficiency and scalability are explained. Common algorithms for online ordering like user authentication, input validation and cart management are also outlined. An example algorithm for multiplying two numbers is provided to illustrate the step-by-step process. Finally, a sample algorithm for an online ordering system is presented, outlining the necessary steps from browsing products to checkout.

Uploaded by

Martina Divino
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
268 views

Module For PHP ICT 9

The document provides an introduction to creating an online ordering form using PHP, JavaScript, and SQL. It discusses the importance of algorithms and flowcharts in programming. It begins by defining an algorithm as a set of steps to solve a problem. Key aspects of algorithms like correctness, readability, efficiency and scalability are explained. Common algorithms for online ordering like user authentication, input validation and cart management are also outlined. An example algorithm for multiplying two numbers is provided to illustrate the step-by-step process. Finally, a sample algorithm for an online ordering system is presented, outlining the necessary steps from browsing products to checkout.

Uploaded by

Martina Divino
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

CREATING AN ONLINE ORDERING FORM USING PHP, JAVASCRIPT, AND SQL: A PROGRAMMING 101 WITH

ALGORITHM AND FLOWCHART

1 | ICT 9 – WEB DEVELOPMENT (PHP)


INTRODUCTION

Welcome to the module on "Creating an Online Ordering Form using PHP, JavaScript, and SQL: A Programming
101 with Algorithm and Flowchart"! In today's digital era, understanding the fundamentals of programming is
an essential skill that empowers you to create innovative solutions to real-world problems. In this module, we will
guide you through the process of building an online ordering form using three powerful technologies: PHP,
JavaScript, and SQL. Additionally, we will provide you with a solid foundation in algorithmic thinking and
flowchart design, which are crucial aspects of the programming process.

To kick-start our learning journey, we will begin by introducing you to the basic principles of programming and
algorithmic thinking. You will learn how to break down complex problems into smaller, manageable steps and
develop logical and efficient algorithms to solve them. We will explore various programming concepts such as
variables, data types, conditionals, loops, and functions. By grasping these fundamental concepts, you will
acquire the necessary building blocks to develop robust and well-structured programs.

Next, we will delve into the world of web development and explore how PHP, JavaScript, and SQL can be used
together to create an online ordering form. We will start by explaining the role of PHP, a server-side scripting
language that enables dynamic content generation. You will learn how to handle form submissions, validate
user input, and interact with a database using PHP. Furthermore, we will introduce JavaScript, a client-side
scripting language, to enhance the interactivity and user experience of your online ordering form. You will
discover how to validate form data on the client-side, perform dynamic updates, and handle events using
JavaScript. Lastly, we will explore SQL, which allows you to store and retrieve data from a database. You will
learn how to design a database schema, create tables, and execute SQL queries to manage order information
and customer details.

In addition to learning these programming languages, we will emphasize the importance of algorithm design
and flowcharting. You will gain the skills to visualize and plan your program's logic using flowcharts, which
provide a graphical representation of the sequential steps and decision-making processes involved. By
incorporating algorithmic thinking and flowcharting into your programming workflow, you will develop a
structured and organized approach to problem-solving.

By the end of this module, you will have acquired a solid foundation in programming concepts, algorithmic
thinking, and the integration of PHP, JavaScript, and SQL. You will be equipped with the skills to create a fully
functional online ordering form and translate your ideas into well-designed and efficient programs. Whether
you are a beginner taking your first steps in programming or an aspiring web developer looking to expand your
skill set, this module will empower you to create dynamic and interactive web applications.

So, let's embark on this exciting journey of creating an online ordering form using PHP, JavaScript, and SQL,
while honing your programming skills and mastering the art of algorithm design and flowcharting. Get ready to
unlock the world of web development and witness the power of programming in action!

2 | ICT 9 – WEB DEVELOPMENT (PHP)


I. ALGORITHM AND FLOWCHART

Lesson 1: ALGORITHM
Welcome, learners, to "Creating an Online Ordering Form Using PHP, JavaScript, and SQL: A Programming 101
with Algorithm and Flowchart." In this module, we will embark on a journey to explore the world of online
ordering forms and how we can implement them using three fundamental programming languages: PHP,
JavaScript, and SQL. In this context, our focus will be on understanding the role of algorithms in designing
efficient and effective online ordering systems.

What is an Algorithm?

In computer programming terms, an algorithm is a set of well-defined instructions to solve a particular problem.
It takes a set of input(s) and produces the desired output. For example,

 An algorithm to add two numbers:


 Take two number inputs
 Add numbers using the + operator
 Display the result

An algorithm is a step-by-step procedure or a set of well-defined instructions to solve a specific problem or


accomplish a particular task.

Algorithms form the foundation of any software development process. They provide a systematic approach to
problem-solving and help us design efficient and reliable solutions.

Algorithms play a vital role in online ordering systems, as they help streamline the ordering process, ensure
accurate data processing, and enhance user experience.

Qualities of a Good Algorithm

1. Correctness: Input and output should be defined precisely. An algorithm should produce the correct
output for any given input.
2. Readability: Each step in the algorithm should be clear and unambiguous or in other words an algorithm
should be easy to understand and maintain.
3. Efficiency: Algorithms should be most effective among many different ways to solve a problem. An
algorithm should be designed to execute in a reasonable amount of time and consume minimal system
resources.
4. Scalability: An algorithm shouldn't include computer code. Instead, the algorithm should be written in
such a way that it can be used in different programming languages. An algorithm should be able to
handle varying input sizes without a significant impact on performance.

Designing Algorithms for Online Ordering Forms

It is important to know that prior to creating of an online ordering system, we must need to take necessary steps
to ensure that the project that we will executing will work properly. In order for us to meet that goal, we must
keep in mind the essential things in creating a system. The following are the things that we need to remember
when we are creating an algorithm pertaining to our planned website.

a. Problem identification: Clearly define the problem that the online ordering form needs to solve.

b. Break down the problem: Divide the problem into smaller subproblems to simplify the solution
approach.

c. Step-by-step instructions: Develop a set of precise instructions to guide the ordering process,
considering user interactions and system requirements.

d. Pseudocode and flowchart: Represent the algorithm using pseudocode and flowcharts, which
provide a visual representation of the solution.

Common Algorithms in Online Ordering Forms

a. User authentication: Verify user credentials and permissions.

b. Input validation: Ensure that user inputs are valid and meet specific criteria.

c. Cart management: Add, remove, and update items in the shopping cart.
3 | ICT 9 – WEB DEVELOPMENT (PHP)
d. Order processing: Handle the order placement, payment processing, and confirmation.

e. Data storage and retrieval: Store and retrieve order details from a database using SQL.

The above context focuses on how we will apply the algorithm in our website creation. As we mentioned earlier,
Algorithms are typically written in a step-by-step fashion, but this is not always the case. Algorithm writing is a
process that occurs after the problem domain has been well-defined. That is, you must be aware of the problem
domain for which you are developing a solution.

Example

Now, use an example to learn how to write algorithms.

Problem: Create an algorithm that multiplies two numbers and displays the output.

Step 1 − Start

Step 2 − declare three integers x, y & z

Step 3 − define values of x & y

Step 4 − multiply values of x & y

Step 5 − store result of step 4 to z

Step 6 − print z

Step 7 − Stop

Algorithms instruct programmers on how to write code. In addition, the algorithm can be written as:

Step 1 − Start mul

Step 2 − get values of x & y

Step 3 − z ← x * y

Step 4 − display z

Step 5 − Stop

Now, what does it look like an algorithm of an online ordering system. Let’s take a look the below example.

1. Start
2. Present the user with a homepage displaying featured products or product categories
3. Allow the user to browse the available products without requiring them to log in or sign up
4. If the user decides to view the details of a specific product, display the product information,
including the name, description, price, and any available options (e.g., size, color)
5. Provide the option to add the product to the shopping cart or continue browsing other
products.
6. If the user adds the product to the shopping cart, update the cart to reflect the added item
and display a confirmation message.
7. Allow the user to proceed to the checkout process or continue shopping
a. If the user chooses to continue shopping, return to step 3
b. If the user decides to proceed to checkout, prompt them to log in or create a new
account
8. If the user is new, collect their information and create a new account
9. If the user is an existing customer, verify their login credentials
10. If the login is successful, proceed to the next step; otherwise, display an error message and
return to step 9
11. Display the contents of the shopping cart, including the selected items and their quantities
12. Provide options to remove items from the cart or update the quantities
13. Calculate the total cost of the items in the shopping cart
14. Prompt the user to provide shipping and payment information
4 | ICT 9 – WEB DEVELOPMENT (PHP)
15. Validate the provided information to ensure its accuracy and completeness
16. If the information is valid, process the payment and place the order; otherwise, display error
messages and return to step 16
17. Display a confirmation message to the user, including the order details and estimated delivery
time
18. End

Lesson 2: Flowchart Overview and Definition

A flowchart is simply a graphical representation of steps. It shows steps in sequential order and is
widely used in presenting the flow of algorithms, workflow or processes. Typically, a flowchart shows
the steps as boxes of various kinds, and their order by connecting them with arrows.

What is a Flowchart?

A flowchart is a graphical representations of steps. It was originated from computer science as a tool
for representing algorithms and programming logic but had extended to use in all other kinds of
processes. Nowadays, flowcharts play an extremely important role in displaying information and
assisting reasoning. They help us visualize complex processes, or make explicit the structure of
problems and tasks. A flowchart can also be used to define a process or project to be implemented.
5 | ICT 9 – WEB DEVELOPMENT (PHP)
Flowchart Symbols

Different flowchart shapes have different conventional meanings. The meanings of some of the more
common shapes are as follows:

1. Terminator

The terminator symbol represents the starting or ending point of the system.

2. Process

A box indicates some particular operation.

3. Document

This represents a printout, such as a document or a report.

4. Decision

A diamond represents a decision or branching point. Lines coming out from the diamond indicates
different possible situations, leading to different sub-processes.

5. Data (input/output)

It represents information entering or leaving the system. An input might be an order from a customer.
Output can be a product to be delivered.

6. On-Page Reference

This symbol would contain a letter inside. It indicates that the flow continues on a matching symbol
containing the same letter somewhere else on the same page.

7. Off-Page Reference

This symbol would contain a letter inside. It indicates that the flow continues on a matching symbol
containing the same letter somewhere else on a different page.

Delay or Bottleneck

6 | ICT 9 – WEB DEVELOPMENT (PHP)


8. Identifies a delay or a bottleneck.

9. Flow

Lines represent the flow of the sequence and direction of a process.

When to Draw Flowchart?

Using a flowchart has a variety of benefits:

1. It helps to clarify complex processes.


2. It identifies steps that do not add value to the internal or external customer, including delays;
needless storage and transportation; unnecessary work, duplication, and added expense;
breakdowns in communication.
3. It helps team members gain a shared understanding of the process and use this knowledge
to collect data, identify problems, focus discussions, and identify resources.
4. It serves as a basis for designing new processes.

Flowchart examples

Here are several flowchart examples. See how you can apply a flowchart practically.

Flowchart Example – Simple Algorithms

A flowchart can also be used in visualizing algorithms, regardless of its complexity. Here is an example
that shows how flowchart can be used in showing a simple summation process.

7 | ICT 9 – WEB DEVELOPMENT (PHP)


Example of Online Ordering Flowchart

8 | ICT 9 – WEB DEVELOPMENT (PHP)


II. CREATING AN ONLINE ORDERING SYSTEM

Lesson 1: Managing Form Data

Learn how to use the method and the action attributes in an HTML form.

The Contact Us page is a combination of HTML and PHP because the page contains an HTML form for the
guests to fill out and the information that they will enter will be processed by PHP and then stored in a database.

Method and Action Attributes

A template for the feedback form found on the Contact Us page has already been designed, but we need to
know how to transfer the user input from the contact.html to a page that can be inserted in our database.

Before passing user input from contact.html to another page, we need to set the attributes of our form so that
it will yield the desirable outcome when we press ‘Send Message’.

The <form> tag has 2 important attributes that need to be set in order for the form to pass the data to another
page, and these attributes are the following:

 action – [URL] specifies where to send the form data when the form is submitted.
 method – [ GET/ POST] specifies the HTTP method to use when sending form data. The GET method
displays the form data on the address bar of the web browser while the POST method sends the form
data to the server behind the sight of the users, thus the POST method is useful if the page requires a
use’s password.

Exercise:
Identify which method is BEST used in each situation. Write GET, if you think the get method would be the best
to use and POST if you think the post method would be the best to use given each situation.

1. You want to search for a specific item on an e-commerce website.


2. You are submitting a form to filter search results by price range.
3. You want to search for a specific item by its unique identifier.
4. You are submitting a form to sort search results by popularity.
5. You are submitting a form to refine search results by size options.
6. You are submitting a form to update the payment due date for a bill.
7. You want to retrieve the current balance of your credit card account.
8. You are submitting a form to delete a saved credit card from your account.
9. You are requesting a receipt for a recent payment transaction.
10. You want to search for a specific transaction in your payment history.
9 | ICT 9 – WEB DEVELOPMENT (PHP)
Given the contact form code below, let’s add an action and a method attribute:

c
o
n
t
a
c
t.
h
t
m
l

After adding an action and a method attribute, the next step is passing these user inputs is to create a PHP file
to receive all the user inputs.

To do that, create a new file in Atom, and save it as contact2.php.

In this empty file, we need to initialize variables to serve as containers of our user input. Like HTML files, we need
to initialize PHP tags before we proceed coding.

Step 1: Initialize <?php and ?.


Step 2: Create a variable to contain all user input such as name, email, contact number, subject and message
in the contact2.php file.
Step 3: Open contact.html and obtain all the names from form.

Note: This step is important and will be used to cross-reference all user input that will be inserted in each variable.

Step 4: In contact2.php, type in $_GET[“form_name”] after each declaration. Use the correct form names so
that the code would work perfectly.

By then you should have:


<?php
$name = $_GET['name'];
contact2.php

$email = $_GET['email'];
$contact = $_GET['contact'];
$subject= $_GET['subject'];
$message = $_GET['message'];
?>

10 | ICT 9 – WEB DEVELOPMENT (PHP)


Step 5: Add echo before the variable to display value of the variable. (e.g. echo #name;)

Note: Every function in PHP must always end with a semi-colon(;).


Code:
<?php
$name = $_GET['name'];
$email = $_GET['email'];
$contact = $_GET['contact'];
$subject= $_GET['subject'];
$message = $_GET['message'];

echo $name . “<br>”;


contact2.php

echo $email . “<br>”;


echo $contact . “<br>”;
echo $subject . “<br>”;
echo $message. “<br>”;
?>

Step 6: (OPTIONAL) : Add <html> and <body> tags before and after the <?php ?> tags to add page breaks in
the PHP code.

Note: Even though the file is in PHP, we can still add <html> tags.

Step 7: Save the file.

Note: Save the file within the folder that is inside the server. File URL:
C:\xampp\htdocs\foldername\contact2.php

Step 8: Run the contact.html file. Since PHP requires a server to run, we can access the file through our web
browser by typing this into the URL bar: https://localhost/folder%20name/contact.html

Note: Spaces in the URL are represented as %20. For example, the folder name My Healthy Option became
My%20Healthy%20Option.

After pressing the Send Message button, your browser will look like this:

11 | ICT 9 – WEB DEVELOPMENT (PHP)


In using GET as a method, we can see that the URL contains all the information inputted by the user. Given the
example above, the URL of the submitted form is:
https://localhost/My%20Healthy%20Option/contact.php?name=Archie+Clarks&email=super.archie%40yahoo
.com&contactnum=&subject=Contratulations%21%message=Thank+you+for+reaching+us+here+in+the+US+b
y+going+worldwide%21

In showing the guest’s input, we used a PHP function echo. The function ‘echo’ displays the value of the
variable that follows the word ‘echo’. This function can either print strings, integers, or arrays. It is also important
not to forget to end the PHP statements with a semi-colon,

Note: A string is a collection of multiple characters. An integer is a number value. An array is a collection of the
same data type, for example, a collection of 4 strings. Semi-colons are used to end a line of code executed;
this may be an echo function or a variable declaration.

From the code above, we used a period (.) to concatenate the variable with a string that in HTML will be
interpreted as a line break. Concatenation is the term for joining two variables from the end of the first variable
to the start of the second, which is similar to what we did above. For example, the code echo $name. “</br>
concatenated the value of $name to a string in HTML.

Lesson 2: DESIGNING DATABASE USING phpMyAdmin

Learn how to create a database and tables.

Now that we have an HTML form for the Contact Us page, the question is, where will we put the information
filled in by the guests? The answer to this question is by storing the form data in the database. But first, let’s
define database.

A database is a structured collection of data. It is a form of data storage that can be represented by a table.
The data is organized in tables so that it can easily be accessed, managed, and updated. Developers usually
employ database in storing the data inputted in an HTML form. And since it stores data in table form, it can be
easily accessed and reorganized by the developers in a number of ways.

Now that you are knowledgeable on database, let’s now proceed to learning how to use the tool in managing
a database. phpMyAdmin is a free and open source tool that is written in PHP, which is intended to handle the
administration of MySQL with the use of a web browser. It has a user-friendly interface that can perform various
tasks like SQL features such as creating, modifying or deleting databases, tables, fields, or rows, managing user
accounts and permission, and executing SQL query.

Creating a Database

To proceed to creating a database, first, you should open phpMyAdmin. And to open phpMyAdmin type in
localhost/phpMyAdmin to the web browser. The phpMyAdmin homepage will be seen on the screen.

12 | ICT 9 – WEB DEVELOPMENT (PHP)


Then, click the Databases tab and enter the database name and press the Create button. For example, let’s
create a my_healthy_option database:

After creating a database, a confirmation message will be shown:

To make sure that the database has been created, you can look at the left side of your screen and find folder
name (e.g. my_healthy_option) there:

13 | ICT 9 – WEB DEVELOPMENT (PHP)


Creating a Table

Now that we have a database for the website, we can now create tables inside the database because a
database without a table is useless. To create one, click on your database (e.g. my_healthy_option) then the
Create Table button on the left side of your screen. Enter contact_us as your table name and do not forget to
fill out all the properties needed to complete your table’s information and before pressing the Save button.

The following are properties that need to be inputted:


1. * Name
o Your preferred column name (e.g. id, store, contact_num)
o Make sure that the name describes the function of the column
2. *Type
o Type refers to the type of data which will be stored in the corresponding field.
3. * Length/ Values
o Length/ Values refer to the length of the data that will be stored.
4. Collation (optional) - refers to the rules that determine how characters are compared and sorted in a
database. It defines the character set and the ordering of characters within that set.
5. Attributes (optional) - attributes refer to the characteristics or properties of a database table's columns.
Each column in a table can have its own set of attributes, which define various aspects of the data
stored in that column.

Here are some commonly used attributes in phpMyAdmin:

 Data Type: The data type attribute specifies the type of data that can be stored in a
column, such as an integer, string, date, or boolean.

 Length/Size: For string data types, the length attribute defines the maximum number of
characters that can be stored in the column. For numeric data types, it may specify the
maximum number of digits allowed.

 Nullability: The nullability attribute indicates whether a column can contain NULL values
or not. If a column is set to allow NULL values, it means the column can be left empty or
have no value assigned to it.

 Default Value: The default value attribute specifies a default value that will be assigned
to the column if no value is explicitly provided during an insert operation.

 Auto Increment: The auto increment attribute is typically used for integer columns and
automatically assigns a unique value to the column for each new row inserted. It is often
used for primary key columns to ensure uniqueness.

 Indexing: The indexing attribute allows you to specify whether a column should be
indexed or not. Indexing improves the performance of search operations by creating a
data structure that allows for faster lookup of values in the column.

6. NULL (optional)
o The field value can be NULL.
7. Index (optional)
o This is where you will assign a key (primary, foreign, index)
8. Default (optional)
o This property allows you to set the default value for the field.
9. Extra / A_I (optional)
o This lets you define whether the field value is auto – increment.
o This is commonly used to define the value of the “id” (primary key).

14 | ICT 9 – WEB DEVELOPMENT (PHP)


10. Comments (optional)
o Comments will be included in the database SQL code.

NOTE: The properties with an asterisk (*) are required fields to be filled out in order to successfully create the
table.

Now that you know what properties are important, let’s start filling out the table.

Creating contact_us Table

Since the Contact us form only needs the guests’ full name, email, contact number, subject, and their
comments or suggestions, we can enter guest_id, fullname, email, contact, subject, and message as field
names inside our table. However, the default number of columns that phpMyAdmin creates for the user is only
4 columns. For this purpose, we have to add 2 more because 4 columns are not enough for our desired table.

The data types for each of them are INT, VARCHAR, VARCHAR, VARCHAR, VARCHAR and TEXT respectively.
The length/ values would be 10,80,50,30,30, and1000.

To give you more information about the most common data types, you can refer to this table.

Data Types Description


INT  It is a data type used to store whole numbers without any decimal
places. The INT type is commonly used for representing numerical
values that are expected to be whole numbers, such as IDs, counts, or
quantities. In phpMyAdmin, when defining a table structure or
creating a column, you can choose the "INT" data type to store integer
values.
 Allows whole numbers between -2,147,483,648 and 2,147,483,647.
 is a data type used to store small integer values. It is similar to the "INT"
TINYINT data type but has a smaller range of values it can represent.
 The TINYINT data type typically occupies 1 byte of storage and can
store integer values ranging from -128 to 127 (signed) or 0 to 255
(unsigned). It is commonly used to store Boolean values (0 or 1), where
0 represents false and 1 represents true.
 Allows whole numbers from 0 to 255.
 Variable–length character string.
VARCHAR  The VARCHAR data type allows you to store alphanumeric or textual
data of varying lengths. When defining a column with VARCHAR data
type in PhpMyAdmin, you need to specify the maximum length of the
string that can be stored. The maximum length can range from 1 to
65,535 characters.

15 | ICT 9 – WEB DEVELOPMENT (PHP)


CHAR  Fixed-length character strings. The CHAR data type allows you to store
alphanumeric or textual data of a fixed length. When defining a
column with CHAR data type in phpMyAdmin, you need to specify the
maximum length of the string that can be stored. The maximum length
can range from 0 to 255 characters.
 CHAR is useful when you have a column with a consistent length
requirement for each stored value. For example, if you have a column
to store postal codes, which are always a fixed length in a particular
country, you can define that column as CHAR (5) if the postal code is
always 5 characters long.
TEXT  data type used to store large amounts of textual data.
 The TEXT data type is designed to store large strings of text, such as
paragraphs, articles, or any other text-based content. It can hold up
to 65,535 characters of data.
DATE  Data type used to store date values.
 The DATE data type is specifically designed to store dates in the format
"YYYY-MM-DD". It represents a specific calendar date, including the
year, month, and day
 When defining a column with the DATE data type in PHPMyAdmin, you
can store dates ranging from '1000-01-01' to '9999-12-31'. The format
ensures that dates are stored consistently and can be easily
manipulated or compared using date functions.

Note: Be sure to define the right attribute size so that all inputs register properly into the database, otherwise the
excess data won’t be stored.

After that, check the NULL property of contact. This means that if the guest did not fill out the contact number
field in the form, the contact will automatically be set to NULL. Next, check the A_I property of the guest_id so
that when a guest fills out the form, the guest_id will be automatically incremented and assigned as a primary
key of the table. A primary key is a field in a table that uniquely identifies each row or record in a database
table.

When you’re done entering, just click the Save button so everything you entered will be saved. To check if the
table has been created, it can be seen at the left side of the screen or displayed after you clicked the Save
button:

16 | ICT 9 – WEB DEVELOPMENT (PHP)


Extension Activity:

Create an exercise_log database with a table that will store your exercise log per day, similar to the sample
exercise log below. Apply the correct data type and to set the correct primary key.

17 | ICT 9 – WEB DEVELOPMENT (PHP)


Lesson 3: Establishing Database Connection

Learn how to establish database connection using PHP built-in function.

After passing user inputs from HTML form to a PHP file, we can now manipulate where they will go. We need to
store all information in a database that can hold all user comments and suggestions. Before we can do that,
we must learn how to connect to a database.

Database Connection

mysqli_connect() is a PHP built-in function that opens a non-persistent MySQL connection. This built-in function
should be created with 4 parameters: the server, username, password, and database name. Also, make sure
to apply an error message to the database connection using the die() function which will return the connection
if successful and returns an error message if there’s a failure in the connection.

For example:

$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

$connection = mysqli_connect($host, $username, $password, $database);

// Check if the connection was successful


if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}

// Connection successful, perform database operations...

// Close the connection when you're done


mysqli_close($connection);
In the example above, replace 'localhost', 'your_username', 'your_password', and 'your_database' with your
actual MySQL server details.

Remember to close the connection using mysqli_close when you have finished working with the database.

Database Selection

Upon connecting to the database, you have to select which database to use when executing the SQL query.
To do this, use mysqli_select_db() function and insert the database name and the variable where you store the
database connection. mysqli_select_db() is a PHP built in function for the database selection.

mysqli_select_db() is used to select a MySQL database on the current database connection. However, it is
important to note that mysqli_select_db() is not commonly used with MySQLi because you can specify the
database during the connection phase using the mysqli_connect() function.

$conn = mysqli_connect($servername, $username, $password, $database);

For example:
mysqli_select_db(“my_healthy_option”, $conn) or die (“cannot connect to database.”)’

Note: The or die () function will only execute when the first condition is not met.

Query Execution

If you have connected to and selected a database, you can now execute the SQL queries. But before you
can execute it, you have to store the SQL query to a variable (usually $query) for easier application of the
mysqli_query() function. The function has 2 parameters which are the variable $query, where you store the SQL
query, and the variable $conn, where you store the database connection.

For example:

18 | ICT 9 – WEB DEVELOPMENT (PHP)


$query = (“SELECT * FROM nutrition ORDER BY p_type”)’
$result = mysqli_query ($query, $conn);

Database Disconnection

When executing MySQL queries or managing database records has been completed, make sure to always
close the connection with the database even if PHP automatically closes the connection when the script ends.
The mysqli_close() function is used to end the connection and it should be placed right after the codes that
manage that database.

UNDERSTANDING THE SQL

SQL (Structured Query Language) is a standard language for accessing databases. The following are the
functions of SQL:
 SQL can execute queries against as database
 SQL can retrieve data from a database.
 SQL can input records into a database.
 SQL can update records in a database.
 SQL can delete records from a database.
 SQL can create new databases.
 SQL can create new tables in a database.
 SQL can create stored procedures in a database.
 SQL can create views in a database.
 SQL can set permissions on tables, procedures, and views.

To build a website that shows some data from a database, you will need the following:
 An RDMS database program (i.e. MS Access, SQL Server, MySQL)
 RDBMS stands for Relational Database Management System. It is a software system that
manages relational databases. A relational database organizes data into tables, where
each table consists of rows and columns. RDBMS provides mechanisms for storing,
retrieving, updating, and managing relational data.
 RDBMS systems use structured query language (SQL) for defining and manipulating the
data in the database. SQL allows users to create, modify, and retrieve data from the
database using standardized syntax and commands.
 A server-side scripting language, like PHP or ASP.
 SQL
 HTML/ CSS

In phpMyAdmin, we can perform SQL queries that will manage our database. Let’s try to perform a SELECT *
query to the database (e.g. my_healthy_option) by using the SQL tab. To do this, click on the database (e.g.
my_healthy_option) > contact_us table > SQL tab. Enter the SELECT * query on the field and click the Go button.

phpMyAdmin: SQL Tab

After executing the SELECT * query, phpMyAdmin will display the contents of the contact_us table. The SQL tab
is useful in checking if your SQL query works before generating the PHP code.

In inserting form data to the database, we will be using the INSERT query. The INSERT INTO statement is used to
insert a new row in a table. There are two possible forms in formulating the statement. The first one is seen below:

INSERT INTOtable_name VALUE (value1, value2, value3,…)

19 | ICT 9 – WEB DEVELOPMENT (PHP)


The first form does not define the columns where the data will be inserted, so the data can be inserted into a
different column. However, the second form specifies both the columns and the values to be inserted. The
general code for the second form is as follows:
INSERT INTO table_name (column1, column2, column3,…) VALUES (value1, value2, value3,…)

The second form of insertion is the most commonly used and is generally preferred because this ensures that
the data is inserted into the specified column.

Going Back to Contact Us

Contact Us Form Answered

<?php Note:
$name = $_POST['name'];
$email = $_POST['email'];  balites_eatery in this code is the
$contact = $_POST['contact'];
database name (so you must
$subject= $_POST['subject'];
$message = $_POST['message']; change the name according to your
database name.
$conn = new mysqli("localhost", "root", "", "balites_eatery");  contact_us is the table name
if ($conn->connect_error) { (change it according to your table
die("Connection Failed: " . $conn->connect_error); name.
}

$sql = "INSERT INTO contact_us (fullname, email, contact, subject, message) VALUES ('$name', '$email',
'$contact', '$subject', '$message')";
if ($conn->query($sql)) {
// Success message
echo "<h2> Thank you for your insight, ".$name."! We'll improve on it. </h2></br>";
} else {
// Error message
echo "Query Error";
}

$conn->close();
echo "<a href='index.php'><h2>go back </h2></a>";

?>
The if else statement above shows that if the query fails to execute, it will echo the error message”Query Error”.
When successfully executed, the result of the code will be:

20 | ICT 9 – WEB DEVELOPMENT (PHP)


Exercise:

Fill in the blanks. Write the correct answer on the blank provided.

1. Is a parameter inside the PHP function that is used to return connection failure.
2. and are the parameters inside the PHP function
mysqli_select_db().
3. A PHP built-in function that builds a non-persistent connection with the database is .
4. A PHP built-in function that is used to execute SQL queries is ______________________.
5. is a function that is used to return a connection failure.
6. Is a parameter that is used to authenticate used to provide identify or to gain
access to the database.
7. Is a PHP built-in function that is used to close the connection with the database.
8. A parameter that specifies what server to connect to is called the .
9. The function for closing the connection with the database has parameters.
10. A parameter that specifies the name used to login to the database is called the .

SESSION 3
ADMIN DUTIES
In this session, you will learn how to create admin pages for managing the whole website. The parts of the
admin pages for managing the whole website. The parts of the admin pages are similar to those of the guest
pages. However, their difference lies in the modifiability of contents, which is permissible on admin pages but
not on guest pages.

Lesson 4: Admin Viewing Guest Insights


Lesson 5: Admin Login Page

21 | ICT 9 – WEB DEVELOPMENT (PHP)


Lesson 4: Admin Viewing Guest Insights
Learn how to create a sorted guest’s insights page for admin viewing.

Now that we’re almost finished our website( e.g. Balites Eatery, My Healthy Option) we have to create an admin
page for viewing and controlling the contents of the guests’ insights page.

Admin View Guest Insights

The guest’ insights page should display the comments and suggestions of the guests to help the admin improve
the website. However, this page should be reflective of the admin’s preferences in terms of function and
organization of content. A uniform layout for the admin pages – one that is similar to the guest pages, except
for the contents and navigation buttons – is ideal in order to establish formality given the nature of the website.

But before we start coding, another attribute called ‘status’ needs to be added to the table. This attribute
indicates the status of each row as ‘read’ or ‘unread’. To add the status attribute, let’s access phpMyAdmin
and then open the contact_us table in our database. The status will initially be ‘unread’ and the admin can
change it to ‘read’ by clicking the Read button.

To add a column to our table, click on contact_us table> Structure tab > add 1 column at the end of the table
> press Go

A new screen will then appear and once this occurs, enter the following codes: status as field name, TINYINT as
type, 4 as length/ value, and set the default property as As defined: 0.

Note: Since the Default property of status is 0, every time you will fill out the Contact Us form, its status value will
be 0.

After clicking the Save button, the outcome should be as follows:

Lay outing Admin Page for Guest Insights

Now that the contact_us table is already complete, we’re ready to begin coding. Let’s start by chancing the
navigation buttons of the page.

Insight.php
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
<meta charset="utf-8">
<title>balites Eatery | Insight</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="header">
<div id="logo">
<img id="logo" src="image/balites eatery.png" alt="logo" class="head">
<h2>Enjoy the food and feel the breeze!</h2>
</div>
</div>
<div id="navigation">

22 | ICT 9 – WEB DEVELOPMENT (PHP)


<ul>
<li><a href="add_product.php">Add Product</a></li>
<li><a href="edit_products.php">Edit Products</a></li>
<li><a href="announcement.php">U & A</a></li>
<li><a href="orders.php">User's Orders</a></li>
<li><a class="active" href="insight.php">User's Insight</a></li>
<li><a href="logout.php">Log Out</a></li>
</ul>
</div>
<div id="container">
<div id="content">
<div id="message_edit" class="top">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<b>Arrange according to:</b>
<select name="column">
<option value="status">Status</option>
<option value="fullname">Name</option>
<option value="subject">Subject</option>
</select>
<b>by:</b>
<select name="order">
<option value="asc">Ascending</option>
<option value="desc">Descending</option>
</select>
<input type="submit" name="go" value="Go">
</form>
<br>
<?php
$conn = new mysqli("localhost", "root", "", "balites_eatery");
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}

function writetable($do, $conn)


{
if (isset($_POST['delete'])) {
$DeleteQuery = "DELETE FROM contact_us WHERE guest_id='" . $_POST['hidden'] . "'";
mysqli_query($conn, $DeleteQuery);
}

if (isset($_POST['read'])) {
$ReadQuery = "UPDATE contact_us SET status='1' WHERE guest_id='" . $_POST['hidden'] . "'";
mysqli_query($conn, $ReadQuery);
}

if (isset($_POST['go'])) {
$select = "SELECT * FROM contact_us ORDER BY " . $_POST['column'] . " " . $_POST['order'];
$result = mysqli_query($conn, $select);
}

echo "<table>
<tr>
<th>Name</th>
<th>E-mail Address</th>
<th>Contact Numbers</th>
<th>Subject</th>
<th>Message</th>
</tr>";

while ($record = mysqli_fetch_array($do)) {


echo "<tr>
<form action='" . $_SERVER['PHP_SELF'] . "' method='post'>
<input type='hidden' name='hidden' value='" . $record['guest_id'] . "'>
<td>" . $record['fullname'] . "</td>
<td>" . $record['email'] . "</td>
<td>" . $record['contact'] . "</td>
<td>" . $record['subject'] . "</td>
<td>" . $record['message'] . "</td>";

if ($record['status'] == 0) {

23 | ICT 9 – WEB DEVELOPMENT (PHP)


echo "<td><input type='submit' name='read' value='Read'></td>";
}

echo "<td>
<input type='submit' name='delete' value='Delete'>
</td>
</form>
</tr>";
}

echo "</table>";
$conn->close();
}

$do = mysqli_query($conn, "SELECT * FROM contact_us ORDER BY status");


writetable($do, $conn);
?>
</div>
</div>
</div>
<div id="footer">
Copyright 2013. Balites Eatery. All Rights Reserved.
</div>
</body>

</html>

For this page, there will only be 5 navigation buttons namely, Add Product, Edit Products, U&A, User’s Orders,
User’s Insight and Log out. Since this will be the User’s Insights page, we have to change the class of user’s
insight into active.

To be able to display the contents from the contact_us table, we must create another <div> under the content
<div> to be labeled “message_edit” which will contain a table with labels and its contents. Before we can
retrieve the contents of the table from the database, we must connect to the database and select the
database we’ll be connecting to:

$conn = new mysqli("localhost", "root", "", "balites_eatery");


if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
Now that we’re connected to the database, we will create a function called writetable(). This function is not
a PHP built – in function but a user-defined function which means that the function is named and created by
the programmers themselves. The purpose of this function is to create a table that will retrieve the contents
from the database.

Also, there is another PHP built-in function that we used inside the while loop parameter namely,
mysqli_fetch_array(). This function is used to return the first row from the database as an associative and/or
numeric array. Each call to mysqli_fetch_array() return the next row in the database table.

We used the while loop through all the data in the database table. We also used $record[‘column name’]
inside the loop to get the data under the specified columns and we used “$record” to store the data that
mysqli_fetch_array($do) will fetch. The while loop will terminate when no more data is left to obtain.

The table will look like this:

Another PHP built-in function that we used in the code above is the isset() function. The isset() function is used
to check whether a variable is set or not. So, in our case, we used the isset() function to check if the Delete and
Read button is clicked. If the Delete button is clicked, the DELETE FROM statement is used to delete the row

24 | ICT 9 – WEB DEVELOPMENT (PHP)


selected. The WHERE clause is also used to extract only the row that fulfills a specified criterion, which is the
guest ID.

However, if the Read button is clicked, the value of status, the column that we added earlier, will be modified
into 1 by using the UPDATE statement. The WHERE clause is also used to specify the guest ID. The purpose of this
Read button is to mark the row as ‘read’ if the admin has finished reading it.

After executing the delete and update query, we executed the SELECT query and combined it with the ORDER
BY clause to show the sorted contents of the database table and then used the writetable() function to encode
the contents into the table.

Before publishing the table on the page, the admin may choose how its contents should be organized. To allow
content organization choices, we should add a form that consists of two dropdown menus, giving the option
to choose the category or column and how the contents will be sorted.

The variable $result contains the execution of the SELECT statement in which the variable will be the parameter
inside the function writetable(). The SELECT statement is used to select data from a database. In our case, the
query SELECT*FROM contact_us means you are selecting all rows from the contact_us database table.
However, since the ORDER BY clause is added to the SELECT * FROM statement, this means that you are
selecting all rows from the contact_us table and arranging them in ascending or descending order, depending
on the admin’s preference.
After executing the SELECT query which allows retrieval of the specified contents from the database, we now
used the writetable() function to write the contents to the table.

Admin Page: User’s Insights

Lesson 5: Admin Login

The Admin Log-in Page ensures security in content management which only the admin can perform. This
involves both accessing and modifying the website’s contents. It is necessary for the admin to login first before
he or she can access pages such as the Homepage, Products and Contact Us pages. The screenshot below
shows what an Admin Log-in Page looks like:

Admin Page: Login

The first step in creating an Admin Log-in Page is to create a new database table where the admin username
and password will be stored. Create a table inside your database (e.g. balites eatery) with the name log_in.

25 | ICT 9 – WEB DEVELOPMENT (PHP)


The table will only store the username and password of admin users, hence, only two fields are created:
username with attributes (VARCHAR, 8, Primary) and password with attributes (VARCHAR,8). Click Save to
continue.

Inserting Data Inside the Database Table

To insert database inside the database table, click on the Insert tab of log_in table then type admin as your
username and password as your password so that it is easy to remember. These fields will later be used to cross
reference the user input to the database for authentication of the admin website.

The admin login has the same layout as other web pages in the website. It has the header </div>, content
</div>, and footer </div>. However, changes will have to be made to the navigation<div> where the links will
be placed, and the content <div>, where the contents will be encoded. A login form basically has two input
fields: one is a text type and the other, is a password type. Our code inside content <div> will be as follows:

<div id="loginform">
<img src="image/lock.png"><h2> Admin Log - in </h2>
<table>

<form action="check.php" method="post">


<tr>
<td>Username</td>
<td>:</td>
<td><input name="myusername" type="text"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="password" maxlength="8"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
log_in.php

</form>
</table>

</div>

26 | ICT 9 – WEB DEVELOPMENT (PHP)


In creating a password-protected website, it is best to practice the use of the method POST. The POST method
safely submits admin input without showing the variables and values in the browser’s URL whenever submitted.
Another important thing to remember is to set the input form type of the password field into type=”password”;
this will render a dot per character display whenever the admin inputs values. This helps avoid possible password
confidentiality breaches.

Note: save the file as log_in.php and design accordingly.

Page After Login

After the admin has already inputted the correct username and password, the form will redirect to check.php
file. The code inside check.php is presented below:
check.php

<?php
session_start();

This will create a session where the user will be able to access all the applications present on a website. A PHP
session variable is used to store information about or change settings for a user session. Session variables hold
information about one singe user, and are available to all pages in one application. To start a session,
session_start(); must be declared on top of the PHP page.

Next, we’ll have to create a connection with the database:


check.php

$conn = new mysqli("localhost", "root", "", "balites_eatery");


if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}

A database connection to your website will ensure correct login.


check.php

$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];

Note: $_POST gets user inputs from the form in log_in.php where the method attribute is set to POST.
check.php

$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);

Note: The striplashes() function removes backslashes.


check.php

$myusername = mysqli_real_escape_string($conn, $myusername);


$mypassword = mysqli_real_escape_string($conn, $mypassword);

Note: The mysqli_real_escape_string() function disregards special characters in a string when used in an SQL
statement.

The following characters are affected.


 \x00  ‘
 \n  “
 \r  \xla
 \ 

This function returns the escaped string on success, or FALSE on failure.

27 | ICT 9 – WEB DEVELOPMENT (PHP)


check.php
$sql = "SELECT * FROM log_in WHERE username ='$myusername' and password = '$mypassword'";

$sql is a PHP variable that will store the SQL statement that will be used. This statement will take all information
from the username and password column in the database table, then compare them to the admin input
$myusername and $mypassword. Once successfully executed, the code will continue.
check.php

$result = $conn->query($sql); // Use $conn->query() instead of mysqli_query()

Note: $result will store all the information taken from the database using the SQL query.
check.php

$count = mysqli_num_rows($result);

Note: The mysqli_num_rows() function returns the number of rows in a recodset. This function returns FALSE on
failure.

Once executed, $count will store the value. If the value is 1, which signals that the admin has correctly set the
username and password, the $_SESSION will be executed, generating a GLOBAL SESSION variable that will be
accessible all throughout the admin website.
check.php

if ($count === 1) {
$_SESSION['is_logged_in'] = 1;
}

Once the SESSION is set, another conditional statement will be prompted; if the SESSION is still unset(e.g.
incorrect username or password), it will return to the log_in.php page. If it is set correctly, the check.php will
redirect the admin to the insight.php page.

if(!isset($_SESSION['is_logged_in']))
{
header("Location:log_in.php");
check.php

} else {
header("Location:insight.php");
}
?>

Note: The header() function sends a raw HTTP header to a client. This means that you will be redirected to the
specified page.

check.php
<?php
session_start();

$conn = new mysqli("localhost", "root", "", "balites_eatery");


if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}

$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];

$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);

$myusername = mysqli_real_escape_string($conn, $myusername);


28 | ICT 9 – WEB DEVELOPMENT (PHP)
$mypassword = mysqli_real_escape_string($conn, $mypassword);

$sql = "SELECT * FROM log_in WHERE username ='$myusername' and password = '$mypassword'";
$result = $conn->query($sql);

$count = mysqli_num_rows($result);
if ($count === 1) {
$_SESSION['is_logged_in'] = 1;
header("Location: insight.php");
exit();
} else {
header("Location: log_in.php");
exit();
}
?>

Admin Login Authentication

The admin should be the only user who can access the insights.php page. To verify this, we have to create
authenticate.php or an authentication page. This will check whether the admin has correctly inputted the
username and password. The code for authenticate.php is seen below:
authenticate.php

<?php
session_start();
if (!isset($_SESSION['is_logged_in'])) {
header("Location: /Balites Eatery/log_in.php");
exit();
}
?>

If the GLOBAL SESSION variable ‘is_logged_in’ is unset, this code will redirect to the admin login page,
log_in.php. Use this file at the beginning of every code to ensure that only authenticated admins will be able
to view or modify items from the website.

Creating Admin Logout

The admin must also have a logout option to ensure that no one will be able to access data without permission.
The code for logout.php is as follows:

<?php
session_start();
session_destroy();
logout.php

header("Location:log_in.php");

?>?>

Note: session_destroy() is a PHP function that completely destroys the session.

EXTENSION ACTIVITY

Create a new database with a table that will be used for storing admins’ usernames and passwords. After
creation, add as many admin usernames and passwords as you want to the database. Then add a page to
your website (e.g. My Healthy Option website) that will display or list down all existing admin, usernames along
with sorting and deleting features.

29 | ICT 9 – WEB DEVELOPMENT (PHP)


SESSION 4
EXPANDING THE WEBSITE
In this session, you will learn how to convert static announcements and updates into a dynamic page whose
homepage the admin will be able to manage and update. Moreover, you will learn how to create a registration
page for non-registered guests who are interested to purchase products online.

Lesson 6: Making Announcements and Updates Dynamic


Lesson 7: Registration Page for Online Buyers

Lesson 6: Making Announcements and Updates Dynamic

Learn how to make announcements and updates dynamic.

Since the sample website (Balite’s Eatery) homepage contains the Announcement and Updates, we’re going
to create an admin page where the admin can modify or edit the contents of the Announcements and
Updates page. In order to do that, we should first create two new database tables that will contain the
Announcements and the Updates.

Adding Database Table for Announcement and Updates

Open phpMyAdmin and create a new table called the announcements. Since this table will only serve as the
container for the announcements, only two attributes are required: announce_id and content. The data types
of the attributes are INT and VARCHAR respectively, and their length/values are and 255. Make sure to check
the A_I property of announce_id to increment its value automatically. Then, chance the Default and NULL
property of content into NULL to disable values, depending on the admin.

Creating Announcements TableA

After completing the attributes, click the save button and create another called the updates. This table will
have the same attributes as the announcements table except that we’ll have to change the table name to
updates and announce_id to update_id. If you have entered the attributes, click the save button.

30 | ICT 9 – WEB DEVELOPMENT (PHP)


Creating Updates table

The newly added Announcements and Updates tables can be seen on the left side of the screen.

Added Announcements and Updates Table

Converting Homepage From HTML to PHP

Now that we have added two database tables for announcements and updates, we have to obrain the
contents from the database and display them onto our homepage. If HTML cannot the contents from the
database, then PHP should be used instead. In order to do this, we only need to change and add a few codes.

First, copy the layout from index.html and paste it to a new document. Save it as index.php since PHP codes
are to be encoded in it.

31 | ICT 9 – WEB DEVELOPMENT (PHP)


<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
<meta charset="utf-8">
<title>Balites Eatery | Home</title>
<link rel="stylesheet" href="styles.css">
</head>

<body>
<div id="header">
<div id="logo">
<img id="logo" src="image/balites eatery.png" alt="logo" class="head">
<h2>Enjoy the food and feel the breeze!</h2>
</div>
</div>
<div id="navigation">
<ul>
<li><a class="active" href="index.php">Home</a></li>
<li><a href="aboutus.php">About Us</a></li>
<li><a href="product.php">Products</a></li>
<li><a href="contact.php">Contact us</a></li>
</ul>
</div>
<div id="container">
index.php

<div id="banner">
<img id="banner" src="image/functionhall.jpg" alt="banner">
</div>

For the content <div>, we will change the codes for the announcements and updates presentation. First, we
will connect to the database because it is where the contents will be obtained:

<div id="content">
<?php
$conn = new mysqli("localhost", "root", "", "balites_eatery");
if ($conn->connect_error) {
index.php

die("Connection Failed: " . $conn->connect_error);


}
?>

To begin, we will import an image (e.g. megaphone.png) file used previously, and then use the SELECT query
to retrieve the announcement from the announcements table in the database. The query must be executed
using mysql_query() function whose result must be passed to the while loop. This loop will be fetch a plethora
of data from the rich database and then ‘echo’ these data for display. The code:

<div id="announcement">
<img src="image/megaphone1.png" alt="announcement" width="150px">
<h2>ANNOUNCEMENTS</h2>
<ul>
<?php
$select_announcement = "SELECT * FROM announcements";
$announcement_result = mysqli_query($conn, $select_announcement);
while ($announcement_record = mysqli_fetch_array($announcement_result)) {
if (!empty($announcement_record['content'])) {
echo "<li> - " . $announcement_record['content'] . " </li>";
}
Index.php

}
?>
</ul>
</div>

As you may notice, the data is displayed using the <ul> or unordered list. This is done so as to follow the original
order of the items included in the list. The announcement <div> code above will result in the same format as
that of index.html:

32 | ICT 9 – WEB DEVELOPMENT (PHP)


Setting up the Updates Section

For our updates <div>, copy the codes of the announcement <div> and change the div id to “updates”. Also,
change SELECT * FROM announcements to SELECT * FROM updates to get the contents from the updates table.
The code is presented on the succeeding page:
<div id="updates">
<img src="image/update.jpg" alt="update" width="150px">
<h2>UPDATES</h2>
<ul>
<?php
$select_update = "SELECT * FROM updates";
$update_result = mysqli_query($conn, $select_update);
while ($update_record = mysqli_fetch_array($update_result)) {
if (!empty($update_record['content'])) {
echo "<li> - " . $update_record['content'] . " </li>";
}
Index.php

}
?>
</ul>
</div>

The code will generate the following outcome:

Admin Edit U&A Page

Now that the homepage is connected to the database, we can proceed to coding the admin page where
the contents of the homepage can be edited by authorized admins. But first, here’s a screencap of the page
in its final published form:

This page is like the User’s insight page wherein only the admin of the website (e.g. Balites Eatery) is allowed to
access. In order to do this, we should require authentication similar to the User’s insights page:

33 | ICT 9 – WEB DEVELOPMENT (PHP)


<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Balites Eatery | U & A</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="header">
<div id="logo">
<img id="logo" src="image/balites eatery.png" alt="logo" class="head">
<h2>Enjoy the food and feel the breeze!</h2>
</div>
</div>
<div id="navigation">
<ul>
<li><a href="add_product">Add Product</a></li>
<li><a href="edit_products.php">Edit Products</a></li>
<li><a class="active" href="announcement.php">U & A</a></li>
<li><a href="orders.php">User's Orders</a></li>
<li><a href="insight.php">User's Insight</a></li>
<li><a href="logout.php">Log Out</a></li>
</ul>
</div>
<div id="container">
<div id="content">
<?php
$conn = new mysqli("localhost", "root", "", "balites_eatery");
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}

function writetable_announcement($x)
{
echo "<table>";
echo "<tr>";
echo "<th>Announcement</th>";
echo "<th>Actions</th>";
echo "</tr>";
while ($record = mysqli_fetch_array($x)) {
echo "<tr>";
echo "<td>" . $record['content'] . "</td>";
echo "<td><form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\">
<input type=\"hidden\" name=\"announce_id\" value=\"" . $record['announce_id'] . "\">
<button type=\"submit\" name=\"delete_announcement\">Remove</button>
</form></td>";
echo "</tr>";
}
// Display input field for new announcement
echo "<tr>";
echo "<td>";
echo "<form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\">";
echo "<textarea rows=\"auto\" cols=\"50\" maxlength=\"255\"
name=\"content_announcement\"></textarea>";
echo "<input type=\"submit\" name=\"update_announcement\" value=\"Update\">";
echo "</form>";
echo "</td>";
echo "<td></td>";
echo "</tr>";
echo "</table>";
}
announcement.php

function writetable_update($y)
{
echo "<table>";
echo "<tr>";
echo "<th>Update</th>";
echo "<th>Actions</th>";
echo "</tr>";
while ($record = mysqli_fetch_array($y)) {

34 | ICT 9 – WEB DEVELOPMENT (PHP)


echo "<tr>";
echo "<td>" . $record['content'] . "</td>";
echo "<td><form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\">
<input type=\"hidden\" name=\"update_id\" value=\"" . $record['update_id'] . "\">
<button type=\"submit\" name=\"delete_update\">Remove</button>
</form></td>";
echo "</tr>";
}
// Display input field for new update
echo "<tr>";
echo "<td>";
echo "<form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\">";
echo "<textarea rows=\"auto\" cols=\"50\" maxlength=\"255\"
name=\"new_update\"></textarea>";
echo "<input type=\"submit\" name=\"add_update\" value=\"Add Update\">";
echo "</form>";
echo "</td>";
echo "<td></td>";
echo "</tr>";
echo "</table>";
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {


if (isset($_POST['update_announcement'])) {
$announcement = $_POST['content_announcement'];
$insertQuery_announcement = "INSERT INTO announcements (content) VALUES
('$announcement')";
mysqli_query($conn, $insertQuery_announcement);
echo "<h5>Successfully added announcement!</h5>";
}

if (isset($_POST['add_update'])) {
$new_update = $_POST['new_update'];
$insertQuery_update = "INSERT INTO updates (content) VALUES ('$new_update')";
mysqli_query($conn, $insertQuery_update);
echo "<h5>Successfully added update!</h5>";
}

if (isset($_POST['delete_announcement'])) {
$announce_id = $_POST['announce_id'];
$deleteQuery_announcement = "DELETE FROM announcements WHERE
announce_id='$announce_id'";
mysqli_query($conn, $deleteQuery_announcement);
echo "<h5>Successfully deleted announcement!</h5>";
}

if (isset($_POST['delete_update'])) {
$update_id = $_POST['update_id'];
$deleteQuery_update = "DELETE FROM updates WHERE update_id='$update_id'";
mysqli_query($conn, $deleteQuery_update);
echo "<h5>Successfully deleted update!</h5>";
}
}

$select_announcement = "SELECT * FROM announcements";


$announcements_result = mysqli_query($conn, $select_announcement);

$select_update = "SELECT * FROM updates";


$updates_result = mysqli_query($conn, $select_update);
?>

<div id="content">
<div id="message_edit">
<?php
writetable_announcement($announcements_result);
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
writetable_update($updates_result);
?>

35 | ICT 9 – WEB DEVELOPMENT (PHP)


</form>
<h5 style="text-align: center; color:red;">Note: Announcements and Updates must not exceed
255 characters.</style></h5>
</div>
</div>
</div>
</div>

<div id="footer">
Copyright 2013. Balites Eatery. All Rights Reserved.
</div>
</body>
</html>

Let's go through the PHP code in the provided HTML code:

 $conn = new mysqli("localhost", "root", "", "balites_eatery");: This line establishes a connection to a MySQL
database using the mysqli extension. It connects to the database named "balites_eatery" on the
localhost (assuming the database server is running on the same machine). The username is set to "root"
and the password is empty ("").
 if ($conn->connect_error) { die("Connection Failed: " . $conn->connect_error); }: This block of code
checks if the database connection was successful. If there is an error, it terminates the script and displays
an error message.
 function writetable_announcement($x) { ... }: This is a PHP function definition. The function
writetable_announcement takes a parameter $x, which is expected to be a result set returned from a
database query. This function is responsible for generating an HTML table based on the data in the result
set.
 function writetable_update($y) { ... }: This is another PHP function definition. The function
writetable_update takes a parameter $y, which is expected to be a result set returned from a database
query. This function is responsible for generating an HTML table based on the data in the result set.
 if ($_SERVER["REQUEST_METHOD"] === "POST") { ... }: This block of code checks if the HTTP request method
is POST. If it is, it means that a form on the page has been submitted, and the code inside this block
handles the form data.
 if (isset($_POST['update_announcement'])) { ... }: This condition checks if the form with the name
update_announcement has been submitted. If it has, the code inside this block is executed. It retrieves
the value of the input field named content_announcement from the submitted form and inserts it into
the announcements table in the database.
 if (isset($_POST['add_update'])) { ... }: This condition checks if the form with the name add_update has
been submitted. If it has, the code inside this block is executed. It retrieves the value of the input field
named new_update from the submitted form and inserts it into the updates table in the database.
 if (isset($_POST['delete_announcement'])) { ... }: This condition checks if the form with the name
delete_announcement has been submitted. If it has, the code inside this block is executed. It retrieves
the value of the hidden input field named announce_id from the submitted form and deletes the
corresponding announcement from the announcements table in the database.
 if (isset($_POST['delete_update'])) { ... }: This condition checks if the form with the name delete_update
has been submitted. If it has, the code inside this block is executed. It retrieves the value of the hidden
input field named update_id from the submitted form and deletes the corresponding update from the
updates table in the database.
 $select_announcement = "SELECT * FROM announcements";: This SQL query selects all rows from the
announcements table in the database.
 $announcements_result = mysqli_query($conn, $select_announcement);: This line executes the SQL
query defined in the previous step and stores the result set in the variable $announcements_result.
 $select_update = "SELECT * FROM updates";: This SQL query selects all rows from the updates table in
the database.
 $updates_result = mysqli_query($conn, $select_update);: This line executes the SQL query defined in the
previous step and stores the result set in the variable $updates_result.
 writetable_announcement($announcements_result);: This calls the writetable_announcement function,
passing the $announcements_result variable as an argument. It generates an HTML table based on the
data in the $announcements_result result set.
 writetable_update($updates_result);: This calls the writetable_update function, passing the
$updates_result variable as an argument. It generates an HTML table based on the data in the
$updates_result result set.

36 | ICT 9 – WEB DEVELOPMENT (PHP)


Admin Page: Updates and Announcement Page

Exercise

Essay Questions:

1. What are the steps involved in creating two new database tables for announcements and updates?
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________

2. How can the contents of the announcements and updates tables be obtained from the database and
displayed on the homepage?
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________

3. What changes need to be made to the HTML code to convert the homepage from HTML to PHP?
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________

4. How can the admin page be created to allow authorized admins to edit the contents of the
homepage?
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________

5. Explain the PHP code used in the admin page to handle the addition, deletion, and updating of
announcements and updates.
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________

Lesson 7: Registration Page for Online Buyers

37 | ICT 9 – WEB DEVELOPMENT (PHP)


Learn how to create a registration page and apply error handling to guest’s inputs.

Before guests can place orders in your website, it is important that the site is able to store their personal
information (e.g. name, address, contact number, etc.) in one way or another. To achieve this, we need to
add a registration form that allows guests to freely sign-up and create profiles that display their personal
information. This will not only prove convenient for the admins of the page as it will make processing of orders
more efficient, but it will also be helpful to the guests themselves as it eliminates the hassle of having to retype
personal details every time they purchase products on the website.

Adding Database Table for Guest Profiles

The first thing we have to create is a new database table for storing guest’s personal information which were
provided upon accomplishing the registration form. To do this, open phpMyAdmin, click your database
(e.g.balites_eatery) and create a new table called user_profile.

Enter user_id, fname, sname,bdate, email, contact, mobile, address and user_pass
as field names since these are the basic information we need from our guest in order
to purchase a product. Next, enter the following data types: INT, VARCHAR,
VARCHAR, DATE, VARCHAR, VARCHAR, VARCHAR, VARCHAR and VARCHAR
respectively. As the length/values of each of the field names specified earlier, enter
11, 50,50, blank, 70,200,200,255,and 8.

It is also important to chec the A_I property of user_id to increment the value
automatically. Aside from this, check the NULL property of contact since the user
can leave it blank. After setting up the following attributes of the table, click the
Save button.

The new table that has been added will appear in the list of previous tables created
on the left side of your screen:

38 | ICT 9 – WEB DEVELOPMENT (PHP)


Since the guests cannot register the same email address twice, we must set email as a UNIQUE key meaning.
This will prohibit the guest to enter an email value that has already been stored in the database. To do this,
open the user_profile table> fin email> click on the UNIQUE icon:

user_profile structure

GUEST LOGIN PAGE

Before creating a registration page, a login page should be developed first so that existing members can log
into their account. Part of the login page is a link to the registration page which guests can access if they wish
to create an account. Here is a screencap of the Guest Login page

Guest Login Page

Link to the Registration Page

Guest Login Page

Creating a Login Form

login.php

?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Balites Eatery| User Log_in</title>
<link rel="stylesheet" href="styles.css">
<style media="screen">
#content{
width: 960px;
margin-left: 10%;
padding-top: 10px;
padding-bottom: 10px;
}
.lock {
display: flex;

39 | ICT 9 – WEB DEVELOPMENT (PHP)


align-items: center;
}

.lock img {
width: 100px;
margin-right: 10px; /* Adjust this value as needed */
}
.lock h2 {
margin: 0;
}
#loginform table{
padding-top: 20px;
margin-left: 30px;
}
</style>
</head>
<body>
<div id="header">
<div id="logo">
<img id ="logo" src="image/balites eatery.png" alt="logo" class="head" >
<h2> Enjoy the food and feel the breeze!</h2>
</div>
</div>
<div id="navigation">
<ul>
<li><a class="active" href="index.php">Home</a></li>
<li><a href="aboutus.php">About Us</a></li>
<li><a href="product.php">Products</a></li>
<li><a href="contact.php">Contact us</a></li>
</ul>
</div>
<div id="content">
<div id="loginform">
<div class="lock">
<img src="image/lock.png" alt="lock" style="width:75px;">
<h2>LOG-IN</h2>
</div>
<table>
<form action="check_user.php" method="post">
<tr>
<td>E-mail</td>
<td>:</td>
<td><input type="email" name="email" style="padding: 5px; width:200px;"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="password" name="pass" maxlength="8" style="padding: 5px;
width:200px;"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
<?php
session_start();

// Retrieve the error message from the URL parameter


$error_message = isset($_GET['error_message']) ? $_GET['error_message'] : '';

// Display the error message


if (!empty($error_message)) {
echo "<p style='color: red;'>{$error_message}</p>";
}
?>
</form>
</table>
<table>
<tr>

40 | ICT 9 – WEB DEVELOPMENT (PHP)


<td>Online order form is available for our account holders.</td>
</tr>
<tr>
<td>If you do not have an account. Click <a href="register.php">here </a> to Register.</td>
</tr>
</table>
</div>
</div>
<div id="footer">
Copyright 2013. Balites Eatery. All Rights Reserved.
</div>
</body>
</html>
Notice that there are two &nbsp; codes inside the table. This code usually represents a non-breaking space.
However, in the form we are creating, we used this to have two empty table cells before inserting the Login
button. The said button is found in the same column as the text boxes.

Note: Once the guest has filled out the form, he or she will be redirected to a page called check_user.php to
verify whether information supplied matches.

The form is enclosed in a table for a more organized presentation in terms of alignment and adaptation of the
CSS design of the table.

Please note that there is a PHP script within the HTML tag. Let us go through with it.

1. if (!empty($error_message)) - This line checks if the $error_message variable is not empty. The empty()
function is a built-in PHP function that returns true if the variable is empty or false otherwise. By using
the negation operator (!), we are checking if the $error_message is not empty.

2. echo "<p style='color: red;'>{$error_message}</p>"; - If the $error_message is not empty, this line will be
executed. It uses the echo statement to output an HTML paragraph element (<p>) containing the
error message. The style='color: red;' attribute sets the text color of the paragraph to red, making it
visually stand out as an error message. The error message itself is displayed within the paragraph using
curly braces ({$error_message}), which allows the value of the $error_message variable to be inserted
into the HTML string.

In summary, this portion of code checks if the error message exists and, if so, outputs an HTML paragraph
element with the error message displayed in red. This provides a visual indication of the error to the user on
the screen.

Note: Guests who have yet to open an account on the site may click the “Click here link” in order to
automatically be redirected to the registration page.

41 | ICT 9 – WEB DEVELOPMENT (PHP)


Guest Registration Page

Now that we have a Guest Login page which is linked to the Registration page, a new file register.php for the
registration page may now be created. But first, here’s the screencap of the registration page that we’re
planning to make:

Registration Form

To get the output above, here is the code:


register.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>register</title>
<link rel="stylesheet" href="styles.css">

<style>

.register{
width: 100px;
height: 100px;
}
#registration{
width: 960px;
height: auto;
font-family: 'Bookman Old Style';
font-size: 14px;
color: #333333;
padding-top: 30px;
display: flex;
margin-top: 20px;
}
#registration h2{
padding-top: 30px;
padding-left: 30px;
}
#content table input{
width: 300px;

42 | ICT 9 – WEB DEVELOPMENT (PHP)


}
#content table td{
padding-left: 5px;
padding-right: 5px;
padding-bottom: 10px;
}
#content b{
color: #FF0000;
margin: auto;
}
#content table input[type=text]{
padding: 10px;
}
#content table input[type=password]{
padding: 10px;
}
#content table input[type=email]{
padding: 10px;
}
</style>
</head>
<body>
<div id="header">
<div id="logo">
<img id="logo" src="image/balites eatery.png" alt="logo" class="head">
<h2>Enjoy the food and feel the breeze!</h2>
</div>
</div>
<div id="navigation">
<ul>
<li><a class="active" href="index.php">Home</a></li>
<li><a href="aboutus.php">About Us</a></li>
<li><a href="product.php">Products</a></li>
<li><a href="contact.php">Contact us</a></li>
</ul>
</div>
<div id="container">
<div id="content">
<div id="registration">
<img src="image/register.png" alt="register" class="register" style="padding-top: 20px;">
<h2>NEW ACCOUNT</h2>
</div>
<?php
$reg = false; // Define the variable $reg with an initial value
$sname = ''; // Initialize the $sname variable
$fname = ''; // Initialize the $fname variable
$bday = ''; // Initialize the $bday variable
$email = ''; // Initialize the $email variable
$contact = ''; // Initialize the contact
$mobile = ''; // Initialize the mobile
$address = ''; // Initialize the address
$pass = ''; // Initialize the password
$rpass = ''; // Initialize the repeat password

if (isset($_POST['reg'])) {
$conn = new mysqli("localhost", "root", "", "balites_eatery");
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
$sname = $_POST['sname'];
$fname = $_POST['fname'];
$bday = $_POST['bday'];
$email = $_POST['email'];
$contact = $_POST['contact'];
$mobile = $_POST['mobile'];
$address = $_POST['add'];
$pass = $_POST['pass'];
$rpass = $_POST['rpass'];

if ($_POST['pass'] === $_POST['rpass']) {

43 | ICT 9 – WEB DEVELOPMENT (PHP)


$insert_query = "INSERT INTO user_profile (fname, sname, bdate, email, contact, mobile, address,
user_pass) VALUES ('$fname', '$sname', '$bday', '$email', '$contact', '$mobile', '$address', '$pass')";
$result = mysqli_query($conn, $insert_query);

if ($result) {
$reg = true;
// Redirect to login page
echo "<h2>Sign-up Successful. You may <a href='login.php'>log-in</a> here.</h2>";
exit; // Stop further script execution
} else {
echo "<b>E-mail is already in use. Please re-type and try another valid e-mail to register.</b><br>";
$reg = false;
}
} else {
echo "<b>Passwords do not match.</b><br>";
$reg = false;
}
}
?>
<br>
<br>
<?php if (!$reg) : ?>
<table>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<tr>
<td>Surname <b>*</b></td>
<td>:</td>
<td><input name="sname" type="text" value="<?php echo $sname; ?>" required></td>
</tr>
<tr>
<td>First Name <b>*</b></td>
<td>:</td>
<td><input name="fname" type="text" value="<?php echo $fname; ?>" required></td>
</tr>
<tr>
<td>Birthdate (yyyy-mm-dd) <b>*</b></td>
<td>:</td>
<td><input name="bday" type="text" value="<?php echo $bday; ?>" required></td>
</tr>
<tr>
<td>E-mail <b>*</b></td>
<td>:</td>
<td><input name="email" type="email" value="<?php echo $email; ?>" required></td>
</tr>
<tr>
<td>Contact No.</td>
<td>:</td>
<td><input name="contact" type="text" value="<?php echo $contact; ?>"></td>
</tr>
<tr>
<td>Mobile No. <b>*</b></td>
<td>:</td>
<td><input name="mobile" type="text" value="<?php echo $mobile; ?>"></td>
</tr>
<tr>
<td>Address <b>*</b></td>
<td>:</td>
<td><input name="add" type="text" value="<?php echo $address; ?>" required></td>
</tr>
<tr>
<td>Password (8 characters max.)<b>*</b></td>
<td>:</td>
<td><input name="pass" type="password" value="<?php echo $pass; ?>" required></td>
</tr>
<tr>
<td>Repeat Password <b>*</b></td>
<td>:</td>
<td><input name="rpass" type="password" value="<?php echo $rpass; ?>" required></td>
</tr>
<tr>

44 | ICT 9 – WEB DEVELOPMENT (PHP)


<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="reg" value="Register"></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="clear" value="Reset"></td>
</tr>
</form>
</table>
<b>All fields with * are required.</b>
<br>
<br>
<h4 style="text-align: center; font-family:"Bookman Old Style";>If you sign-up already, you may <a
href="login.php"> log-in </a> here!</h4>
<?php endif; ?>

</div>
</div>
<div id="footer">
Copyright 2013. Balites Eatery. All Rights Reserved.
</div>
</body>
</html>

Let's go through it line by line for the PHP script of registration form to understand its functionality:

1. <?php: This is the opening tag for a PHP script.


2. $reg = false;: This line declares a variable called $reg and assigns it the initial value of false. It will be
used later to track the success of the registration process.
3. The next several lines ($sname, $fname, $bday, $email, $contact, $mobile, $address, $pass, and $rpass)
initialize variables that will hold the values submitted by the user through the registration form. They are
all initially set to empty strings.
4. if (isset($_POST['reg'])) {: This line checks if the form has been submitted with the name attribute 'reg' as
a POST variable. In other words, it checks if the user has clicked the "Register" button.
5. Inside the if block, a database connection is established using the mysqli class with the provided
credentials.
6. If the connection to the database fails, the script terminates and displays an error message.
7. The script assigns the submitted form values to their respective variables ($sname, $fname, $bday,
$email, $contact, $mobile, $address, $pass, and $rpass).
8. Next, the script checks if the entered password and repeat password match using the condition if
($_POST['pass'] === $_POST['rpass']).
9. If the passwords match, an SQL query is constructed to insert the user's details into the user_profile table
in the database.
10. The query is executed using mysqli_query().
11. If the query is successful, the $reg variable is set to true, indicating a successful registration. A success
message is echoed, providing a link to the login page, and the script is exited using exit.
12. If the query fails, an error message is displayed indicating that the email is already in use. The $reg
variable is set to false.
13. If the passwords do not match, an error message is displayed, and the $reg variable is set to false.
14. The closing brace } indicates the end of the if block for checking the registration form submission.
15. The following lines (?>, <br>, <br>) are plain HTML code.
16. <?php if (!$reg) : ?>: This line starts a PHP block that checks if the $reg variable is false. If it is, the
subsequent HTML code will be executed.
17. The code inside this block is an HTML form for user registration, which includes various input fields for the
user's details.
18. The input fields are pre-populated with the values from the previous form submission (if any), using PHP
echo statements (value="<?php echo $variable; ?>").
19. The form has two submit buttons, one for registration and another for resetting the form.
20. The form is wrapped within an HTML table for layout purposes.
21. The remaining lines (</table>, <b>All fields with * are required.</b>, <br>, <br>, and the link to the login
page) are HTML code.
22. <?php endif; ?>: This line ends the PHP block started with <?php if (!$reg) : ?>. It signifies the end of the
condition for displaying the registration form.

45 | ICT 9 – WEB DEVELOPMENT (PHP)


ERROR HANDLING FOR GUEST LOGIN

Having created the Guest Login and Registration form, let’s now create a check_user.php to check if the guest
entered the correct username and password. The code enclosed in check_user.php will be similar to
check.php; however, the guest login requires an email unlike the admin login which requires a username.

check_user.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "balites_eatery";

$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}

$myusername = $_POST['email'];
$mypassword = $_POST['pass'];

$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);

$myusername = mysqli_real_escape_string($conn, $myusername);


$mypassword = mysqli_real_escape_string($conn, $mypassword);

$sql = "SELECT * FROM user_profile WHERE email = ? LIMIT 1";


$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $myusername);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
$record = $result->fetch_assoc();
if ($record['user_pass'] === $mypassword) {
$_SESSION['user_is_logged_in'] = $record['user_id'];
header("Location: order.php");
exit();
} else {
$error_message = "Incorrect password";
header("Location: login.php?error_message=" . urlencode($error_message));
exit();
}
} else {
$error_message = "Incorrect email";
header("Location: login.php?error_message=" . urlencode($error_message));
exit();
}
?>

Let’s go through the provided PHP code line by:

These lines enable error reporting and display errors on the webpage. This
is useful during development or debugging, as it helps to identify and fix
any issues.

This line starts or resumes a session. Sessions allow you to store and retrieve data
across multiple web pages for a particular user.

46 | ICT 9 – WEB DEVELOPMENT (PHP)


These lines define the variables for the database connection.
$servername is set to "localhost", which typically represents the local
machine. $username is set to "root", which is a common default username
for the MySQL database. $password is an empty string, which means there
is no password set. $dbname is set to "balites_eatery", which is the name
of the database being accessed.

These lines establish a database


connection using the MySQLi
(MySQL Improved) extension.
The new mysqli() creates a new
instance of the mysqli class,
representing the database
connection. If the connection fails, the code outputs an error message and terminates the script execution
using die().

These lines retrieve the values entered in the email and pass fields
from a form submitted via the HTTP POST method. The values are
assigned to the variables $myusername and $mypassword,
respectively.

These lines escape special


characters in the values of
$myusername and $mypassword
to prevent SQL injection attacks.
mysqli_real_escape_string() is used to escape the characters using the database connection $conn.

1. The code checks if the variable $result has exactly one row ($result->num_rows === 1). This condition
suggests that the code expects a database query result ($result) to have only one row, indicating that
a user with the given email exists in the system.

2. If the condition in step 1 is true (i.e., there is exactly one row in the result), the code proceeds to fetch
the associative array of the fetched row using $result->fetch_assoc() and assigns it to the variable
$record.

3. The code then compares the value of the 'user_pass' field in the $record array with a variable
$mypassword, which presumably contains the password provided by the user during the login attempt.
If the passwords match ($record['user_pass'] === $mypassword), the code proceeds with the following
actions:

o It sets a session variable named 'user_is_logged_in' to the value of $record['user_id'], which


appears to be the user ID associated with the logged-in user.
o It sends an HTTP Location header to redirect the user's browser to the order.php page.
o The exit() function is called to terminate the script execution.
4. If the password comparison in step 3 fails, indicating an incorrect password, the code sets the error
message variable $error_message to "Incorrect password".

47 | ICT 9 – WEB DEVELOPMENT (PHP)


o It sends an HTTP Location header to redirect the user's browser back to the login.php page,
appending the error message as a query parameter (login.php?error_message=).
o The exit() function is called to terminate the script execution.

5. If the condition in step 1 is false (i.e., there are zero or more than one rows in the result), it means that
the user email is not found or there are duplicate emails in the system. In this case, the code sets the
error message variable $error_message to "Incorrect email".

o It sends an HTTP Location header to redirect the user's browser back to the login.php page,
appending the error message as a query parameter.
o The exit() function is called to terminate the script execution.

Here's an explanation of the functions used in the code:

1. error_reporting(E_ALL): Sets the error reporting level to display all types of errors, warnings, and notices.

2. ini_set('display_errors', 1): Enables the display of errors directly on the webpage.

3. session_start(): Starts a new or resumes an existing session, allowing you to store and retrieve session
data.

4. new mysqli($servername, $username, $password, $dbname): Creates a new instance of the MySQLi
class, establishing a connection to a MySQL database using the provided server, username, password,
and database name.

5. die("Connection Failed: " . $conn->connect_error): Terminates the script execution and displays an error
message if the database connection fails.

6. $_POST['email'] and $_POST['pass']: Retrieve the values submitted via the HTTP POST method with the
input field names 'email' and 'pass' from a form.

7. stripslashes($string): Removes any slashes added to a string. This is commonly used as a security measure
to prevent the misuse of special characters.

8. mysqli_real_escape_string($conn, $string): Escapes special characters in a string using the provided


database connection. It helps prevent SQL injection attacks by ensuring the string is treated as data
rather than executable code.

9. $conn->query($sql): Executes an SQL query on the database using the provided connection and returns
the result. In this code, it executes the SELECT query stored in the $sql variable.

10. $result->num_rows: Retrieves the number of rows returned by the executed SQL query.

11. $result->fetch_assoc(): Fetches the next row from the result set as an associative array.

12. $_SESSION['user_is_logged_in']: Stores the value of the 'user_id' field from the fetched record in a session
variable named 'user_is_logged_in'. It allows the user's login state to persist across multiple pages.

13. header("Location: product.php"): Sends an HTTP redirect header to the browser, instructing it to
navigate to the specified URL, in this case, 'product.php'.

14. exit(): Terminates the script execution immediately.

Once guests have finished browsing or placing orders, they should have an option to logout. The code for
logout_user.php is as follows:

48 | ICT 9 – WEB DEVELOPMENT (PHP)


Let's go through the code line by line:

 <?php
o This is the opening tag for a PHP script. It indicates that the following code is written in PHP.

 session_start();
o This line starts a session in PHP. Sessions are a way to store and retrieve data for a particular user
across multiple pages. By calling session_start(), the script initializes the session or resumes an
existing one.

 session_destroy();
o This line destroys the current session and deletes all session data. session_destroy() function is
used to free all session variables and effectively end the session. After calling this function, the
session data is no longer accessible.

 header("Location: login.php");
o This line sends an HTTP header to redirect the user to the login.php page. The header() function
is used to send raw HTTP headers to the browser. In this case, it sets the Location header to
login.php, which instructs the browser to redirect the user to the specified page.

The purpose of this code seems to be to destroy the current session and redirect the user to the login page,
possibly to log them out or reset their session state.

Exercise:

Matching Type: Match Column A to Column B and write the letter of the correct answer on the blank beside
column A.

Column A Column B
1. Send a raw HTTP header to a client. a. &nbsp
2. The entity used to represent a non-breaking b. PHP_SELF
space.
3. Returns a row from a recordset as a numeric c. ssession_start
array.
4. used to reset session that will lose all stored d. session_destroy()
session data.
5. Specifies which errors are reported e. header()
6. Escaped special characters in a string for use f. stripslashes()
in an SQL statement.
7. Removes backslashes g. mysqli_real_escape_string()
8. used to store session of a single user. h. mysqli_fetch_row()
9. Returns a row from a recordset as an i. mysqli_fetch_array()
associative array/and or a numeric array
10. A variable that returns the current script j. error_reporting()
being executed.

Extension Activity (Performance Task)

Identify different kinds of user errors which will display according to specific errors.

49 | ICT 9 – WEB DEVELOPMENT (PHP)


Below is a health magazine subscription form concept. You need to identify what fields are necessary to store.

Item Importance Error Message


Name e.g. It is important to store the “Please enter your name.”
subscriber’s name.
Address
City
Zip code
E-mail
Contact No.
Months Subscription

What fields do you think are necessary to add to help the administrator know more about the subscriber? Justify
your answer.

SESSION 5
WEBSITE EXPANSION

Now that we have a registration page, we’re going to make the Products page dynamic and create a new
database table for storing the list of products. Apart from this, you will also create another database table for
storing the orders of the guests and connect this table to the user_profile table. When the tables are ready, we
will learn how to create an online order form for the registered guests.

Lesson 8: Products Database


Lesson 9: Orders Database
Lesson 10: Create an Online Order Form

50 | ICT 9 – WEB DEVELOPMENT (PHP)


Lesson 8: Products Database

Learn how to convert the Products page from HTML to PHP and create a New table for storing the products.

Based on the products page previously created your website (e.g. Balites Eatery) has 4 products in a static
HTML page. Creating a ‘products’ table to store the products info makes it easier for the admin to add more
products without modifying the static HTML code of the page. To make this modifiable by the admin, the
Products page must be converted from statis HTML to PHP page which will then be connected to the database.

Adding Database Table for Products

To create a database table go to phpMyAdmin>click on you database (e.g. Balites Eatery) click new to create
a new table. Again, since the default number of columns that phpMyAdmin creates for the user is only 4
columns, add 2 more for the purpose of the products table.

Enter the following as field name inside the products table: product_id, p_name, price, description, p_quantity,
and file. The data types of the following are INT, VARCHAR, INT, VARCHAR, VARCHAR and VARCHAT
respectively, with length/values of 11,100,11,255,50, and 100. Make sure to check the A_I property of
product_id.

51 | ICT 9 – WEB DEVELOPMENT (PHP)


Products Table Structure

The file column will contain the filename of the product’s image. Since images cannot be stored in a database,
we will not be storing the whole image in the database but rather, we will be getting the filename of the images
using an array in PHP.

Click Save button and check if the products table has been added in the database.

Added Products Table

Converting Products Page from HTML to PHP

Now that the products table is ready, we can now proceed to converting the Products page from HTML to
PHP. But first, let’s see how the new PHP page will look like after conversion:

52 | ICT 9 – WEB DEVELOPMENT (PHP)


The Products page in HTML just displays the list of products in tabular form while the page in PHP will have the
same list of products in tabular form but with an ORDER HERE link that will redirect guests to an order form,
however, requiring them to login first. If they do not have an account, there is a link for the registration page.

To begin coding for the products.php page, copy the layout from products.html and add the ORDER HERE link:

product.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>product</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="header">
<div id="logo">
<img src="image/balites eatery.png" alt="logo" class="head">
<h2>Enjoy the food and feel the breeze!</h2>
</div>
</div>
<div id="navigation">
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="aboutus.php">About Us</a></li>
<li><a class="active" href="product.php">Products</a></li>
<li><a href="contact.php">Contact us</a></li>
</ul>
</div>
<div id="container">
<div id="products">
<table id="producttable" cellpadding="10" cellspacing="5" border="1">
<tr>
<th>
<img src="image/logo2.jpg" alt="logo2">
<h2>PRODUCTS</h2><br>
</th>
<th>
<img src="image/cart.png" alt="order">
<a href="login.php"><h2>ORDER HERE</h2></a>
</th>
</tr>

If the ORDER HERE link is clicked, the guest will be redirected to login.php.

53 | ICT 9 – WEB DEVELOPMENT (PHP)


Guest Login Page
Let us see the entire code of the product.php.

product.php
<!-- product.php -->
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>product</title>
<link rel="stylesheet" href="styles.css">
<style media="screen">
#products a {
text-decoration: none;
}
#products img {
padding: 15px;
float: left;
width: 100px;
}
#products th {
border: 0;
}
</style>
</head>
<body>
<div id="header">
<div id="logo">
<img src="image/balites eatery.png" alt="logo" class="head">
<h2>Enjoy the food and feel the breeze!</h2>
</div>
</div>
<div id="navigation">
<ul>
<li><a href="index.php">Home</a></li>
<li><a href="aboutus.php">About Us</a></li>
<li><a class="active" href="product.php">Products</a></li>
<li><a href="contact.php">Contact us</a></li>
</ul>
</div>
<div id="container">
<div id="products">
<table id="producttable" cellpadding="10" cellspacing="5" border="1">
<tr>
<th>
<img src="image/logo2.jpg" alt="logo2">
<h2>PRODUCTS</h2><br>
</th>
<th>
<img src="image/cart.png" alt="order">
<a href="login.php"><h2>ORDER HERE</h2></a>
</th>
</tr>
<?php
54 | ICT 9 – WEB DEVELOPMENT (PHP)
// Database connection
$conn = new mysqli("localhost", "root", "", "balites_eatery");
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}

// Retrieve data from the database


$result = mysqli_query($conn, "SELECT * FROM products");

$data = array();

while ($row = mysqli_fetch_array($result)) {


$data[] = $row;
}

// Loop through the data and generate table rows


for ($i = 0; $i < count($data); $i += 2) {
$row1 = $data[$i];
$row2 = ($i + 1 < count($data)) ? $data[$i + 1] : null;

$imagePath1 = "image/" . $row1['file']; // Default image path if 'image' key is not present
if (isset($row1['image']) && file_exists("image/" . $row1['image'])) {
$imagePath1 = "image/" . $row1['image'];
}

$imagePath2 = "image/" . $row2['file']; // Default image path if 'image' key is not present
if (isset($row2['image']) && file_exists("image/" . $row2['image'])) {
$imagePath2 = "image/" . $row2['image'];
}
?>

<tr>
<td>
<img src="<?php echo $imagePath1; ?>" alt="<?php echo $row1['p_name']; ?>">
<h5><?php echo $row1['p_name']; ?></h5>
<ul>
<?php
// Display the description as list items
$description = $row1['description'];
$tokens = explode("-", $description);
foreach ($tokens as $token) {
echo "<li>" . $token . "</li>";
}
?>
</ul>
<h4>Price: <b><?php echo $row1['price'] . ".00 ";?> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Quantity: <?php echo $row1['p_quantity']; ?></b></h4>
</td>

<?php if ($row2 !== null) { ?>


<td>
<img src="<?php echo $imagePath2; ?>" alt="<?php echo $row2['p_name']; ?>">
<h5><?php echo $row2['p_name']; ?></h5>
<ul>
<?php
// Display the description as list items
$description = $row2['description'];
$tokens = explode("-", $description);
foreach ($tokens as $token) {
echo "<li>" . $token . "</li>";
}
?>
</ul>
<h4>Price: <b><?php echo $row2['price'] . ".00";
?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity: <?php echo $row2['p_quantity']; ?></b></h4>
</td>
<?php } ?>
</tr>

<?php

55 | ICT 9 – WEB DEVELOPMENT (PHP)


}
?>
</table>
</div>
</div>
<div id="footer">
&copy; 2013. Balites Eatery. All Rights Reserved
</div>
</body>
</html>

Let’s go through the PHP code in the given HTML file step by step.

<?php
// Database connection
$conn = new mysqli("localhost", "root", "", "balites_eatery");
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
?>
 This code establishes a connection to the MySQL database using the mysqli extension in PHP. It
connects to the local host (localhost) with the username (root), an empty password (""), and the
database name (balites_eatery). If the connection fails, it displays an error message and stops the
execution using die().

<?php
// Retrieve data from the database
$result = mysqli_query($conn, "SELECT * FROM products");

$data = array();

while ($row = mysqli_fetch_array($result)) {


$data[] = $row;
}
?>
 Here, the code executes an SQL query to fetch all the rows from the "products" table in the database.
It stores the result in the variable $result. Then, an empty array $data is created. The code uses a while
loop to iterate through each row fetched from the result using mysqli_fetch_array(). It appends each
row to the $data array.

<?php
// Loop through the data and generate table rows
for ($i = 0; $i < count($data); $i += 2) {
$row1 = $data[$i];
$row2 = ($i + 1 < count($data)) ? $data[$i + 1] : null;

$imagePath1 = "image/" . $row1['file']; // Default image path if 'image' key is not present
if (isset($row1['image']) && file_exists("image/" . $row1['image'])) {
$imagePath1 = "image/" . $row1['image'];
}

$imagePath2 = "image/" . $row2['file']; // Default image path if 'image' key is not present
if (isset($row2['image']) && file_exists("image/" . $row2['image'])) {
$imagePath2 = "image/" . $row2['image'];
}
?>
 In this section, a for loop is used to iterate over the $data array. It processes the data in pairs to create
table rows. The variable $i is the index for the first item in each pair. Inside the loop, the code assigns
the current pair of data to variables $row1 and $row2.

 Next, it constructs the image paths for the first and second items ($imagePath1 and $imagePath2,
respectively). It concatenates the "image/" directory with the value of the 'file' column from each
row. If the 'image' key exists in the row and the corresponding file exists in the "image/" directory, it
overrides the default image path with the custom one.
<tr>
<td>
<img src="<?php echo $imagePath1; ?>" alt="<?php echo $row1['p_name']; ?>">
<h5><?php echo $row1['p_name']; ?></h5>
<ul>
<?php

56 | ICT 9 – WEB DEVELOPMENT (PHP)


// Display the description as list items
$description = $row1['description'];
$tokens = explode("-", $description);
foreach ($tokens as $token) {
echo "<li>" . $token . "</li>";
}
?>
</ul>
<h4>Price: <b><?php echo $row1['price'] . ".00 ";?> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Quantity:
<?php echo $row1['p_quantity']; ?></b></h4>
</td>

<?php if ($row2 !== null) { ?>


<td>
<img src="<?php echo $imagePath2; ?>" alt="<?php echo $row2['p_name']; ?>">
<h5><?php echo $row2['p_name']; ?></h5>
<ul>
<?php
// Display the description as list items
$description = $row2['description'];
$tokens = explode("-", $description);
foreach ($tokens as $token) {
echo "<li>" . $token . "</li>";
}
?>
</ul>
<h4>Price: <b><?php echo $row2['price'] . ".00"; ?>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Quantity:
<?php echo $row2['p_quantity']; ?></b></h4>
</td>
<?php } ?>
</tr>

 Inside the loop, the code generates HTML table rows (<tr>) and cells (<td>) for each pair of data. It
uses the variables $imagePath1 and $row1 to display the image, product name, description, price,
and quantity of the first item.

 If the $row2 variable is not null (meaning there is a second item in the pair), it generates the HTML
code for the second item using $imagePath2 and $row2.

 The description stored in the database is split into individual items using the explode() function, which
breaks the string into an array using the "-" delimiter. Then, a foreach loop is used to iterate through
each token and display it as a list item (<li>).

<?php } ?>
 This closing tag marks the end of the loop that iterates over the data and generates table rows.

Let's go through the SQL commands and PHP functions used in the code one by one:

SQL Commands:

1. SELECT * FROM products: This SQL command is used to retrieve all rows and columns from the "products"
table. It fetches all the product information from the table.

PHP Functions:

1. mysqli_query(): This function is used to execute an SQL query on the database. In the code, it is used to
execute the SELECT query to fetch the product data from the "products" table.

2. mysqli_fetch_array(): This function is used to fetch a result row as an associative array, a numeric array,
or both from the result set returned by mysqli_query(). It retrieves a row of data from the query result,
and in the code, it is used inside a loop to fetch each row of product data from the result set and store
it in the $data array.

3. explode(): This function is used to split a string into an array of substrings based on a specified delimiter.
In the code, it is used to split the product description stored in the database. The delimiter used is "-",
and each substring is added to the $tokens array.

4. isset(): This function is used to determine if a variable is set and not null. It checks if the specified variable,
in this case, $row1['image'] and $row2['image'], exists in the row and is not null. If the variable is set, it
returns true; otherwise, it returns false.

57 | ICT 9 – WEB DEVELOPMENT (PHP)


5. file_exists(): This function is used to check if a file or directory exists. It takes a file path as an argument
and returns true if the file exists; otherwise, it returns false. In the code, it is used to check if the custom
image file exists in the "image/" directory.

EXERCISE (Written Task)

Identification. Identify the correct item required to finish the equation.

You are system’s developer in a store that My Healthy Option recently established. You are tasked to create
an algorithm that will support all the computation of each product in the store.

$item_price
$quantity
$loyalty_discount[decimal already e.g. 0.10]
$senior_citizen_discount[decimal already e.g. 0.25]

1. Compute the total of a regular customer.

2. Compute for the total of a customer with a loyalty card.

3. Compute for the total of a regular senior citizen

4. Compute for the total of a senior citizen with a loyalty card.

58 | ICT 9 – WEB DEVELOPMENT (PHP)


Lesson 9: Orders Database

Learn how to relate two databases.

Since we now have a user_profile table, we can now proceed to creating an order form. In order to store the
information from the order form, we need to make an orders table and relate it to the user_profile table so that
the admin would know which order belongs to which guest. And to relate the two tables, we need to assign a
foreign key which is the field in a relational table that matches the primary key column of another table. The
foreign key can be used to cross-reference tables which do not require unique values in the referencing
relation.

But before we relate the two tables, we have to create the orders table first.

Adding Database Table for Orders

To create the orders database table, we have to identify we need to store. Basically, when a guest orders from
a website, we need to store which products he or she has ordered, their quantity, price, status, etc. However,
in our website, we only need to store the order_id, user_id, p_id. Quantity, date, status, and total. The data types
and values for each would be INT(11), INT(11), INT(11), INT(11) DATE, TINYINT(4), and INT(11). Then make sure to
mark the A_I property of the order_id. And also, change the default property of quantity and status as As
defined: 0;

Creating Orders Table

59 | ICT 9 – WEB DEVELOPMENT (PHP)


After entering the following, press the Save button and you will see that the
orders table has been added together with the other tables of your database:

Check if you have a similar structure as this:

Orders Table Structure

Connecting Orders Table to User Profile and Products Tables

Now that the three database tables are ready, we have to relate those three tables. To do this, see the structure
of the orders table and clickk on Index icons of user_id and p_id row. After this, click on Relation View, which
can be found in at the under the word Structure.

To connect the Orders table to the User Profile and Products tables in phpMyAdmin, you need to establish
relationships between the tables using foreign keys. Here's a step-by-step guide:

60 | ICT 9 – WEB DEVELOPMENT (PHP)


1. Ensure that the User Profile and Products tables already exist in your database. Each of these tables
should have a primary key column that uniquely identifies each user and product, respectively.

2. Open phpMyAdmin and select the database where your tables reside.

3. Locate the Orders table and make sure it has a column to store the user's ID (foreign key) and another
column to store the product's ID (foreign key). If these columns don't exist, you'll need to add them using
the ALTER TABLE statement.

4. In the Orders table structure view, click on the "Relation view" button located at the top menu. It looks
like three linked tables.

5. In the "Add Foreign Key Constraint" section, select the column that corresponds to the user's ID in the
Orders table.

6. In the "Foreign key constraint" dialog, you will see two dropdown menus. In the first dropdown menu,
select the User Profile table. In the second dropdown menu, select the column that uniquely identifies
each user in the User Profile table.

7. Click on the "Save" button to create the foreign key relationship between the Orders and User Profile
tables.

8. Repeat steps 5-7 for the column that corresponds to the product's ID in the Orders table, selecting the
Products table and its corresponding primary key column.

9. Once you've created the foreign key relationships, you can join the tables in your queries to retrieve
information from all three tables together.

That's it! You have successfully connected the Orders table to the User Profile and Products tables using foreign
keys in phpMyAdmin. Now you can perform queries that involve data from multiple tables, such as retrieving
order details with user and product information.

Exercise: (Performance Task)

You are a database administrator of a clinic, and are tasked to correlate an existing database in order to
efficiently provide medication to your patients. Given the tables below, fill out what data types should be used
in each column. Figure out which items need to be correlated to one another to create an efficient database.

Table: Profile
Id
Name
Address
Telephone
Email
Room_no

Table: Products

61 | ICT 9 – WEB DEVELOPMENT (PHP)


Id
Name
Supplier_id
Price

Table: Supplier
Id
Name
Email
Telephone

Table: Order
Id
User_id
Product_id
Datetime
Delivery_status
Nutritionist_id

Table: Nutritionist
Id
Name

Which columns or tables need to be added or deleted to make the system more efficient in storing data?

62 | ICT 9 – WEB DEVELOPMENT (PHP)


Lesson 10: Creating An Online Order Form

Learn how to create an online order form for the guest.

Now that we have the necessary tables, which are the user_profile and orders table, we need to construct a
guest order form.

order.php
<?php
session_start(); // Start the session

// Database connection
$conn = new mysqli("localhost", "root", "", "balites_eatery");
if ($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}

$id = isset($_SESSION['user_is_logged_in']) ? $_SESSION['user_is_logged_in'] : null;

// Retrieve the first name and last name from the user_profile table
$name_sql = "SELECT fname, sname FROM user_profile WHERE user_id = '$id'";
$name_result = mysqli_query($conn, $name_sql);
$name_row = mysqli_fetch_assoc($name_result);
$fname = isset($name_row['fname']) ? $name_row['fname'] : '';
$sname = isset($name_row['sname']) ? $name_row['sname'] : '';
$username = $fname . ' ' . $sname;
?>

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Balites Eatery | Order</title>
63 | ICT 9 – WEB DEVELOPMENT (PHP)
<link rel="stylesheet" href="styles.css">
<style>
#content{
width: 960px;
margin-left: auto;
margin-right: auto;
}
.image{
display: flex;
align-items: center;
}
img{
width: 100px;
padding: 20px;
}
table tr td{
padding: 10px;
text-align: center;
border: 1px solid black;
}
table{
width: 100%;
border: 1px solid black
}

</style>
</head>
<body>
<div id="header">
<div id="logo">
<img src="image/balites eatery.png" alt="logo" class="head">
<h2>Enjoy the food and feel the breeze!</h2>
</div>
</div>
<div id="navigation">
<ul>
<?php
if ($username) {
echo "<li>Welcome " . $username . "</li>";
}
?>
<li><a class="active" href="order.php">Order</a></li>
<li><a href="confirm.php">Confirmation</a></li>
<li><a href="logout_user.php">Log out</a></li>
</ul>
</div>
<div id="content">
<div id="orderform">
<div class="image">
<img src="image/cart.png" alt="cart">
<h2> ORDER PRODUCTS </h2>
</div>

<?php
$order_form = false;
$sum = 0;

if (isset($_POST['add'])) {
// Check if the 'user_id' exists in the 'user_profile' table
$check_sql = "SELECT * FROM user_profile WHERE user_id = '$id'";
$check_result = mysqli_query($conn, $check_sql);
if (mysqli_num_rows($check_result) > 0) {
// 'user_id' exists, proceed with the INSERT query
$product_id = $_POST['hidden'];
$quantity = 1; // Set the quantity to 1

// Check if the product already exists in the cart for the current day
$check_order_sql = "SELECT * FROM orders WHERE user_id = '$id' AND p_id = '$product_id' AND date =
CURDATE()";
$check_order_result = mysqli_query($conn, $check_order_sql);

64 | ICT 9 – WEB DEVELOPMENT (PHP)


if (mysqli_num_rows($check_order_result) > 0) {
// Update the quantity if the product already exists
$update_order_sql = "UPDATE orders SET quantity = quantity + 1 WHERE user_id = '$id' AND p_id =
'$product_id' AND date = CURDATE()";
mysqli_query($conn, $update_order_sql);
} else {
// Insert the new order with quantity 1
$sql = "INSERT INTO orders (user_id, p_id, quantity, date) VALUES ('$id', '$product_id', $quantity,
CURDATE())";
mysqli_query($conn, $sql);
}

echo "<h5>Successfully added " . $_POST['p_name'] . " to cart</h5>";


$order_form = true;
} else {
// 'user_id' does not exist, handle the error or redirect the user
echo "User not found.";
// You may choose to redirect the user to an error page or take appropriate action.
// For example: header("Location: error.php");
}
} elseif (isset($_POST['remove'])) {
$remove_product_id = $_POST['hidden'];
$remove_sql = "DELETE FROM orders WHERE user_id = '$id' AND p_id = '$remove_product_id' AND date =
CURDATE()";
mysqli_query($conn, $remove_sql);
echo "<h5>Successfully removed " . $_POST['p_name'] . " from cart</h5>";
$order_form = true;
} else {
$order_form = true;
}

if ($order_form) {
$total_sql = "SELECT * FROM orders WHERE user_id='$id' AND status ='0' ORDER BY date DESC";
$total = mysqli_query($conn, $total_sql);
$num_rows = mysqli_num_rows($total); // Check the number of rows returned

if ($num_rows > 0) {
while ($record = mysqli_fetch_array($total)) {
$quantity = $record['quantity'];
$product_id = $record['p_id'];
$product_sql = "SELECT price FROM products WHERE product_id = '$product_id'";
$product_result = mysqli_query($conn, $product_sql);
$product_row = mysqli_fetch_assoc($product_result);
$product_price = isset($product_row['price']) ? $product_row['price'] : 0;
$total_price = $quantity * $product_price;
$sum += $total_price;
}
echo "<h2>Total Amount: P " . $sum . ".00</h2>"; // Display the total amount
} else {
echo "<h2>No items in the cart</h2>";
}
}
?>

<table>
<tr>
<th>Item Name</th>
<th>Price</th>
<th>Add Item</th>
<th>Remove Item</th>
</tr>
<?php
$print_sql = "SELECT * FROM products ORDER BY p_name";
$print = mysqli_query($conn, $print_sql);
while ($table = mysqli_fetch_array($print)) {
$product_id = $table['product_id'];
$product_name = $table['p_name'];
$product_price = isset($table['price']) ? $table['price'] : 0;
$product_quantity = $table['p_quantity'];
?>

65 | ICT 9 – WEB DEVELOPMENT (PHP)


<tr>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="hidden" value="<?php echo $product_id; ?>">
<input type="hidden" name="p_name" value="<?php echo $product_name; ?>">
<td><?php echo $product_name; ?></td>
<td>P <?php echo $product_price; ?>.00 <?php echo $product_quantity; ?></td>
<td>
<?php
$check_sql = "SELECT * FROM orders WHERE user_id='$id' AND status=0 AND p_id='$product_id' AND
date = CURDATE()";
$check = mysqli_query($conn, $check_sql);
$count = mysqli_num_rows($check);

if (!$count) {
?>
<input type="submit" name="add" value="Add Item">
<?php
} else {
echo "<b>Pending in cart</b>";
}
?>
</td>
<td>
<?php
$remove_sql = "SELECT * FROM orders WHERE user_id='$id' AND status=0 AND p_id='$product_id'
AND date = CURDATE()";
$remove_result = mysqli_query($conn, $remove_sql);
$remove_count = mysqli_num_rows($remove_result);

if ($remove_count) {
?>
<input type="submit" name="remove" value="Remove Item">
<?php
}
?>
</td>
</form>
</tr>
<?php } ?>
</table>

<?php
$ptotal_sql = "SELECT * FROM orders WHERE user_id='$id' AND status='1' ORDER BY date DESC";
$ptotal = mysqli_query($conn, $ptotal_sql);
$psum = 0;
while ($record = mysqli_fetch_array($ptotal)) {
$psum += $record['total'];
}

// Remove the payment success message


if (isset($_SESSION['payment_successful'])) {
unset($_SESSION['payment_successful']);
}

mysqli_close($conn);
?>
<form id="proceed" action="confirm.php?<?php echo http_build_query($_POST); ?>" method="post">
<input type="submit" value="Proceed to Confirmation">
</form>
</div>
</div>
<div id="footer">
&copy; 2013. Balites Eatery. All Rights Reserved
</div>
</body>
</html>

Let’s go through with these codes line by line starting with the <?php block:

66 | ICT 9 – WEB DEVELOPMENT (PHP)


1. <?php: This tag indicates the start of a PHP code block.
2. session_start();: This function starts a new or resumes an existing session. It is used to persist data across
multiple pages for a specific user session.
3. Database connection:
 $conn = new mysqli("localhost", "root", "", "balites_eatery");: This line establishes a connection
to the MySQL database server using the mysqli extension. It connects to the "balites_eatery"
database on the local server using the username "root" and an empty password. Change
these values as per your database configuration.
 The subsequent lines check if the connection is successful and display an error message if it
fails.
4. id = isset($_SESSION['user_is_logged_in']) ? $_SESSION['user_is_logged_in'] : null;: This line checks if the
'user_is_logged_in' key is set in the session. If it is set, the value is assigned to the variable '$id'.
Otherwise, '$id' is assigned null.

9-14. Retrieve the first name and last name from the 'user_profile' table:

 $name_sql = "SELECT fname, sname FROM user_profile WHERE user_id = '$id'";: This SQL query selects
the 'fname' (first name) and 'sname' (last name) columns from the 'user_profile' table where the
'user_id' matches the value stored in the '$id' variable.
 $name_result = mysqli_query($conn, $name_sql);: This executes the SQL query using the database
connection.
 $name_row = mysqli_fetch_assoc($name_result);: This retrieves the first row from the result set as an
associative array.
 $fname = isset($name_row['fname']) ? $name_row['fname'] : '';: This assigns the value of 'fname' from
the result row to the '$fname' variable, or assigns an empty string if it is not set.
 $sname = isset($name_row['sname']) ? $name_row['sname'] : '';: This assigns the value of 'sname' from
the result row to the '$sname' variable, or assigns an empty string if it is not set.
 $username = $fname . ' ' . $sname;: This concatenates the first name and last name with a space in
between to form the full username.

19-34. HTML and CSS code:

 This section contains HTML markup and CSS styles for the webpage.

36-53. Navigation menu:

 This section displays a navigation menu using an unordered list (<ul>) and list items (<li>).
 The PHP code within this section checks if the username is set and displays a "Welcome [username]"
message accordingly.

55-232. Order form and logic:

 This section handles the order form and related logic.


 $order_form = false;: This variable is initially set to false.
 $sum = 0;: This variable is initialized to 0 and is used to calculate the total sum of prices for the items in
the cart.
 The code within this section checks if the user has submitted the form to add or remove items from the
cart and performs the corresponding actions.
 It also retrieves the items from the 'orders' table and calculates the total amount by multiplying the
quantity of each item with its price.
 The form inputs and buttons are dynamically generated using PHP within a loop that fetches data
from the 'products' table.
 The code also checks if the items exist in the cart, if they are pending, and displays appropriate
messages and buttons.
 The total amount and the table of items in the cart are displayed using PHP echo statements and
HTML markup.

235-241. Payment calculation and form submission:

 $ptotal_sql = "SELECT * FROM orders WHERE user_id='$id' AND status='1' ORDER BY date DESC";: This SQL
query retrieves the orders with 'status' set to '1' (completed) from the 'orders' table for the current user.
 $psum = 0;: This variable is initialized to 0 and is used to calculate the total payment sum for
completed orders.
 The code within this section calculates the total payment sum by summing the 'total' column values
from the result set.
 The code also removes the payment successful message from the session if it exists.

67 | ICT 9 – WEB DEVELOPMENT (PHP)


 Finally, a form is displayed to proceed to the confirmation page, passing the form data using the POST
method.

244-249. Closing tags and end of the file:

Now let us understand what are the PHP script that is used in order.php and its functions:

1. <?php:
 This is the opening PHP tag that indicates the start of a PHP code block.
2. session_start();:
 This function starts a new or resumes an existing session.
 It is used to enable the usage of session variables to store and retrieve data across multiple
pages for a specific user session.
3. $conn = new mysqli("localhost", "root", "", "balites_eatery");:
 This line establishes a database connection using the mysqli class.
 It creates a new mysqli object with the provided parameters:
 "localhost": The hostname or IP address of the MySQL server.
 "root": The username for the database server.
 "": The password for the database server (empty string in this case).
 "balites_eatery": The name of the database to connect to.
4. $conn->connect_error:
 This property of the $conn object holds the error message if the database connection fails.
5. die("Connection Failed: " . $conn->connect_error);:
 This function terminates the script execution and displays an error message if the database
connection fails.
 The error message includes the error obtained from $conn->connect_error.
6. $id = isset($_SESSION['user_is_logged_in']) ? $_SESSION['user_is_logged_in'] : null;:
 This line uses the ternary operator to check if the session variable 'user_is_logged_in' is set.
 If it is set, the value of 'user_is_logged_in' is assigned to the variable $id.
 If it is not set, $id is assigned null.
7. $name_sql = "SELECT fname, sname FROM user_profile WHERE user_id = '$id'";:
 This variable holds an SQL query string to select the columns 'fname' and 'sname' from the
table 'user_profile' where the 'user_id' matches the value stored in $id.
8. $name_result = mysqli_query($conn, $name_sql);:
 This function executes the SQL query specified in $name_sql using the database connection
$conn.
 It returns a result object ($name_result) that holds the result set returned by the query.
9. $name_row = mysqli_fetch_assoc($name_result);:
 This function fetches a single row from the result set as an associative array.
 The associative array ($name_row) contains column names as keys and column values as
values.
10. $fname = isset($name_row['fname']) ? $name_row['fname'] : '';:
 This line uses the ternary operator to check if the key 'fname' exists in the $name_row array.
 If it exists, the corresponding value is assigned to the variable $fname.
 If it doesn't exist, an empty string is assigned to $fname.
11. $sname = isset($name_row['sname']) ? $name_row['sname'] : '';:
 This line uses the ternary operator to check if the key 'sname' exists in the $name_row array.
 If it exists, the corresponding value is assigned to the variable $sname.
 If it doesn't exist, an empty string is assigned to $sname.
12. $username = $fname . ' ' . $sname;:
 This line concatenates the values of $fname, a space character, and $sname to form the full
name and assigns it to the variable $username.
13. mysqli_query($conn, $sql):
 This function executes an SQL query ($sql) using the database connection $conn.
 It returns a result object containing the result set if applicable.
14. mysqli_fetch_array($result):
 This function fetches a single row from the result set as both a numeric array and an associative
array.
 It returns an array with both numeric and associative keys for each column value.
15. mysqli_num_rows($result):
 This function returns the number of rows in the result set returned by a query.
16. mysqli_close($conn):
 This function closes the database connection represented by the $conn object.

In creation of order.php, we’ve added some JavaScript functionality. Let us go through it:

1. <script>:

68 | ICT 9 – WEB DEVELOPMENT (PHP)


 This is an HTML tag used to define client-side JavaScript code.
2. function submitForm() { ... }:
 This is a JavaScript function declaration named submitForm().
 It is used to handle the form submission event.
3. document.getElementById('paymentForm').addEventListener('submit', submitForm);:
 This line adds an event listener to the form with the ID 'paymentForm'.
 The event listener listens for the form submission event and calls the submitForm() function
when the event occurs.
4. event.preventDefault();:
 This line prevents the default form submission behavior.
 It stops the form from being submitted and allows the JavaScript code to handle the
submission process.
5. var cardNumber = document.getElementById('cardNumber').value;:
 This line retrieves the value of the input field with the ID 'cardNumber'.
 It assigns the value to the variable cardNumber.
6. var cvv = document.getElementById('cvv').value;:
 This line retrieves the value of the input field with the ID 'cvv'.
 It assigns the value to the variable cvv.
7. var expiryDate = document.getElementById('expiryDate').value;:
 This line retrieves the value of the input field with the ID 'expiryDate'.
 It assigns the value to the variable expiryDate.
8. if (cardNumber.length !== 16 || cvv.length !== 3 || expiryDate === '') { ... }:
 This if statement checks if the length of cardNumber is not equal to 16, or the length of cvv is
not equal to 3, or expiryDate is an empty string.
 If any of these conditions are true, it executes the code block within the curly braces.
9. document.getElementById('error').style.display = 'block';:
 This line sets the CSS display property of the element with the ID 'error' to 'block'.
 It makes the error message element visible by changing its display style.
10. return false;:
 This statement terminates the execution of the submitForm() function.
 It prevents the form from being submitted if the validation conditions fail.

JavaScript plays a crucial role in web development. Its primary purpose is to add interactivity and dynamic
behavior to web pages. It enables the manipulation of HTML elements, handling user events, making AJAX
(AJAX (Asynchronous JavaScript and XML) is a web development technique that allows you to send and
retrieve data from a server asynchronously without requiring a full page reload. It combines JavaScript,
XMLHttpRequest (XHR), and sometimes XML or JSON to achieve this functionality.With AJAX, you can make
requests to the server in the background, typically in response to user actions or events, and update parts of a
web page dynamically without disrupting the user's current interaction.) requests to the server, and performing
calculations and validations on the client-side. In the provided code, JavaScript is responsible for handling the
form submission event, retrieving form input values, performing form validation, and displaying error messages.

By using JavaScript, web developers can enhance the user experience, validate user input before sending it
to the server, create dynamic and interactive elements, and perform various tasks on the client-side without
requiring a full page reload.

REFERENCES

https://www.programiz.com/dsa/algorithm
https://www.simplilearn.com/tutorials/data-structure-tutorial/what-is-an-algorithm
https://www.integrify.com/what-is-a-flowchart/
https://www.visual-paradigm.com/tutorials/flowchart-tutorial/
https://www.semanticscholar.org/paper/Food-finder-Mobile-food-ordering-application-Rathod-
ashishrathod/2145d9a780b9ace18fbc5da3225349ec5c34b26b

69 | ICT 9 – WEB DEVELOPMENT (PHP)

You might also like