Module For PHP ICT 9
Module For PHP ICT 9
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!
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,
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.
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.
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.
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
Problem: Create an algorithm that multiplies two numbers and displays the output.
Step 1 − Start
Step 6 − print z
Step 7 − Stop
Algorithms instruct programmers on how to write code. In addition, the algorithm can be written as:
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
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
3. Document
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
9. Flow
Flowchart examples
Here are several flowchart examples. See how you can apply a flowchart practically.
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.
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.
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.
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.
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.
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.
$email = $_GET['email'];
$contact = $_GET['contact'];
$subject= $_GET['subject'];
$message = $_GET['message'];
?>
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.
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:
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.
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.
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:
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.
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).
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.
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.
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:
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.
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";
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.
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:
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.
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.
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:
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.
<?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:
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.
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.
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.
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">
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>";
if ($record['status'] == 0) {
echo "<td>
<input type='submit' name='delete' value='Delete'>
</td>
</form>
</tr>";
}
echo "</table>";
$conn->close();
}
</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:
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.
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
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.
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:
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.
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>
</table>
</div>
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.
$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 mysqli_real_escape_string() function disregards special characters in a string when used in an SQL
statement.
$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
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();
$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($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();
}
?>
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.
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");
?>?>
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.
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.
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.
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.
The newly added Announcements and Updates tables can be seen on the left side of the screen.
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.
<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
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:
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>
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:
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)) {
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>";
}
}
<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);
?>
<div id="footer">
Copyright 2013. Balites Eatery. All Rights Reserved.
</div>
</body>
</html>
$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.
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.
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________
___________________________________________________________________________________________________
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.
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:
user_profile structure
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
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;
.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> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
<?php
session_start();
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.
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
<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;
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 ($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>
</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:
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";
$myusername = $_POST['email'];
$mypassword = $_POST['pass'];
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
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();
}
?>
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.
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.
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:
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.
1. error_reporting(E_ALL): Sets the error reporting level to display all types of errors, warnings, and notices.
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.
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'.
Once guests have finished browsing or placing orders, they should have an option to logout. The code for
logout_user.php is as follows:
<?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.  
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.
Identify different kinds of user errors which will display according to specific errors.
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.
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.
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.
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.
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:
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.
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);
}
$data = array();
$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 ";?>
Quantity: <?php echo $row1['p_quantity']; ?></b></h4>
</td>
<?php
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();
<?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
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.
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]
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.
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;
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:
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.
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
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?
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);
}
// 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);
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'];
?>
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'];
}
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">
© 2013. Balites Eatery. All Rights Reserved
</div>
</body>
</html>
Let’s go through with these codes line by line starting with the <?php block:
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.
This section contains HTML markup and CSS styles for the webpage.
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.
$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.
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>:
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