Ephrem Tesfaye - IP-II - Chapter-Seven
Ephrem Tesfaye - IP-II - Chapter-Seven
Ephrem Tesfaye - IP-II - Chapter-Seven
Topic Contents
Objectives
After studying this chapter, you should be able to:
Understand the concept of relational database
Understand MySQL
Write a clean modular PHP code to connect to MySQL database
Understand how to create alter and delete tables in MySQL
Understand and use PHP to write a back end code to interact with your MySQL
database
Secure and backup your database
Understand and summarize the whole idea behind the course IP-II
Relational databases are, by far, the most commonly used type of database. They depend on a
sound theoretical basis in relational algebra. You don’t need to understand relational theory to use
a relational database (which is a good thing), but you do need to understand some basic relational
database concepts.
Tables
Relational databases are made up of relations, more commonly called tables. A table is exactly
what it sounds like—a table of data.
Example
CUSTOMERS
CustomerID Name Address City
1 Julie Smith 25 Oak Street Airport West
2 Alan Wong 1/47 Haines Avenue Box Hill
3 Michelle Arthur 357 North Road Yarraville
The table has a name (Customers); a number of columns, each corresponding to a different piece
of data; and rows that correspond to individual customers.
Columns
Each column in the table has a unique name and contains different data. Additionally, each column
has an associated data type. For instance, in the Customers table, you can see that CustomerID is
an integer and the other three columns are strings. Columns are sometimes called fields or
attributes.
Rows
Each row in the table represents a different customer. Because of the tabular format, each row has
the same attributes. Rows are also called records or tuples.
Values
Each row consists of a set of individual values that correspond to columns. Each value must have
the data type specified by its column.
Keys
You need to have a way of identifying each specific customer. Names usually aren’t a very good
way of doing this. If you have a common name, you probably understand why. Consider Julie
Smith from the Customers table, for example. If you open your telephone directory, you may find
too many listings of that name to count.
What we have done in this example, and what you will likely do in your applications, is assign a
unique CustomerID. This is the same principle that leads to your having a unique bank account
number or club membership number. It makes storing your details in a database easier. An
artificially assigned identification number can be guaranteed to be unique. Few pieces of real
information, even if used in combination, have this property. The identifying column in a table is
called the key or the primary key.
Databases usually consist of multiple tables and use a key as a reference from one table to another.
The next table shows a second table added to the database. This one stores orders placed by
customers. Each row in the Orders table represents a single order, placed by a single customer.
You know who the customer is because you store her CustomerID.
The relational database term for this relationship is foreign key. CustomerID is the primary key in
Customers, but when it appears in another table, such as Orders, it is referred to as a foreign key.
Schemas
The complete set of table designs for a database is called the database schema. It is akin to a
blueprint for the database. A schema should show the tables along with their columns, the primary
key of each table and any foreign keys. A schema does not include any data, but you might want
to show sample data with your schema to explain what it is for. The schema can be shown in
informal diagrams as we have done, in entity relationship diagrams, or in a text form, such as
Underlined terms in the schema are primary keys in the relation in which they are underlined. Italic
terms are foreign keys in the relation in which they appear italic.
Relationships
Foreign keys represent a relationship between data in two tables. For example, the link from Orders
to Customers represents a relationship between a row in the Orders table and a row in the
Customers table.
Three basic kinds of relationships exist in a relational database. They are classified according to
the number of elements on each side of the relationship. Relationships can be one-to-one, one-to-
many, or many-to-many.
A one-to-one relationship means that one of each thing is used in the relationship. For example, if
you put addresses in a separate table from Customers, they would have a one-to-one relationship
between them. You could have a foreign key from Addresses to Customers or the other way around
(both are not required).
In a one-to-many relationship, one row in one table is linked to many rows in another table. In our
example, one Customer might place many Orders. In these relationships, the table that contains
the many rows has a foreign key to the table with the one row. Here, we put the CustomerID into
the Order table to show the relationship.
In a many-to-many relationship, many rows in one table are linked to many rows in another table.
For example, if you have two tables, Books and Authors, you might find that one book was written
by two coauthors, each of whom had written other books, on their own or possibly with other
authors. This type of relationship usually gets a table all to itself, so you might have Books,
Authors, and Books_Authors. This third table would contain only the keys of the other tables as
foreign keys in pairs, to show which authors are involved with which books.
Activity
What is MySQL?
MySQL has stand-alone clients that allow users to interact directly with a MySQL database using
SQL, but more often, MySQL is used with other programs to implement applications that need
relational database capability. MySQL is a component of the XAMPP web application software
stack (and others), which is an acronym for Cross platform, Apache, MySQL, Perl, PHP. MySQL
is used by many database-driven web applications, including Drupal, Joomla, phpBB, and
WordPress. MySQL is also used by many popular websites, including Facebook, Flickr,
MediaWiki, Twitter, and YouTube.
phpMyAdmin
phpMyAdmin is a costless and open source software that provides the functionality of operating
and managing MySQL over the internet. It provides an ease to the user to control and supervise
the database with the help of a graphic user interface known as phpMyAdmin. This GUI is written
in PHP programming language. Over time it has gained a lot of trust and demand for the purpose
of finding a web-based MySQL administration solution. The user can operate upon MySQL via
phpMyAdmin user interface while still directly executing SQL queries. The GUI allows the host
to carry a number of manipulation operations on the database, such as editing, creating, dropping,
amending, alteration of fields, tables, indexes, etc. It can also be used to manage access control
over the data by giving privileges and permissions. phpMyAdmin has thus a vital role to play in
handling and creating a database.
STEP 1- Navigate to XAMPP in your system or simply launch it by clicking the XAMPP Creating
MySQL Database with XAMPP Icon. The Control Panel is now visible and can be used to initiate
or halt the working of any module.
STEP 2- Click on the "Start" button corresponding to Apache and MySQL modules.
STEP 3- Now click on the "Admin" button corresponding to the MySQL module. This
automatically redirects the user to a web browser to the following address-
http://localhost/phpmyadmin
Using GUI
STEP 1- One can see a number of tabs such as Database, SQL, User Accounts, Export, Import,
Settings, etc. Click on the "Database" tab. Here you can see the Create option. Choose an
appropriate name for the input field titled Database name. Things to keep in mind while selecting
the name for the database are-
Writing Query
We can write a query and execute it on the console window and on the space provided by
PhpMyAdmin for query execution. One can see a number of tabs such as Database, SQL, User
Accounts, Export, Import, Settings, etc. Click on the "SQL" tab. Here you can see an area for an
SQL code to type in. Write your SQL statement here and click “Go” at right bottom corner. And
check the result. This way works for creating and altering database and tables in your database,
meaning any SQL statement is executed exactly like wise.
The SQL statement for creating table will have a syntax as follows:
Using GUI
STEP 1- It is very important to create tables in order to store the information in a systematic
manner. In this step, we will build tables for the created database. In the created Database, click
on the 'Structure' tab. Towards the end of the tables list, the user will see a 'Create Table' option.
Fill the input fields titled "Name" and "Number of Columns" and hit the 'Go' button.
STEP 2- Now, we have to initialize our columns based on their type. Enter the names for each of
your columns, select the type, and the maximum length allowed for the input field. Click on "Save"
in the bottom right corner. The table with the initialized columns has been created. You can create
any number of tables for your database.
Notice
Students are expected to make themselves familiar with the PhpMyAdmin GUI. Since our intention is to generate
skilled programmers, then we will be focusing on the code parts from now on.
Writing Query
We can write a query and execute it on the console window and on the space provided by
PhpMyAdmin for query execution. The SQL statement for creating table will have a syntax as
follows:
A table may have more than one Primary keys, which is most commonly 2 columns in combination
will be used as composite key. Also a table may have more than one foreign keys. These can be
implemented as:
Activity
Based on the schema provided, create all the tables needed for our minimal Bookstore application
Before you can do a lot with a database, you need to store some data in it. The way you most
commonly do this is to use the SQL INSERT statement.
Recall that RDBMSs contain tables, which in turn contain rows of data organized into columns.
Each row in a table normally describes some real-world object or relationship, and the column
values for that row store information about the real-world object. You can use the INSERT
statement to put rows of data into the database.
INSERT [INTO] table [(column1, column2, column3,...)] VALUES (value1, value2, value3,...);
For example, to insert a record into Book-O-Rama’s Customers table, you could type
INSERT INTO Customers VALUES (NULL, 'Julie Smith', '25 Oak Street', 'Airport West');
You can see that we’ve replaced table with the name of the actual table where we want to put the
data and the values with specific values. The values in this example are all enclosed in quotation
marks. Strings should always be enclosed in pairs of single or double quotation marks in MySQL.
Numbers and dates do not need quotes.
There are a few interesting things to note about the INSERT statement. The values specified here
will be used to fill in the table columns in order. If you want to fill in only some of the columns,
or if you want to specify them in a different order, you can list the specific columns in the columns
part of the statement. For example,
INSERT INTO Customers (name, city) VALUES ('Melissa Jones', 'Nar Nar Goon North');
This approach is useful if you have only partial data about a particular record or if some fields in
the record are optional.
Also notice that we specified a NULL value for the CustomerID column when adding Julie Smith
and ignored that column when adding the other customers. You might recall that when you set up
the database, you created CustomerID as the primary key for the Customers table, so this might
seem strange. However, you specified the field as AUTO_INCREMENT. This means that, if you
insert a row with a NULL value or no value in this field, MySQL will generate the next number in
the auto increment sequence and insert it for you automatically. This behavior is pretty useful.
The workhorse of SQL is the SELECT statement. It’s used to retrieve data from a database by
selecting rows that match specified criteria from a table. There are a lot of options and different
ways to use the SELECT statement. The basic form of a SELECT is
SELECT [options]
FROM [tables]
[WHERE conditions]
[GROUP BY group_type]
[ORDER BY order_type]
[LIMIT limit_criteria];
Let’s take some basic and common examples as a revision of some database course features.
This query lists the contents of the Name and City columns from the Customers table:
SELECT *
FROM Order_Items;
To access a subset of the rows in a table, you need to specify some selection criteria. You can do
this with a WHERE clause. For example,
SELECT *
FROM Orders
WHERE CustomerID = 3;
In addition to equality, MySQL supports a full set of operators and regular expressions. The ones
you will most commonly use in WHERE clauses are:
<= Less than or amount <= Tests whether one value is less
equal to 60.00 than or equal to another
!= or <> Not equal quantity != 0 Tests whether two values are not
equal
IS NOT n/a address is not Tests whether a field actually
NULL null contains a value
The last three rows in the table refer to LIKE and REGEXP. They are both forms of pattern
matching.
You can test multiple criteria using the simple operators and the pattern matching syntax and
combine them into more complex criteria with AND and OR. For example,
SELECT *
FROM Orders
WHERE CustomerID = 3 OR CustomerID = 4;
Often, to answer a question from the database, you need to use data from more than one table. For
example, if you wanted to know which customers placed orders this month, you would need to
look at the Customers table and the Orders table. If you also wanted to know what, specifically,
they ordered, you would also need to look at the Order_Items table.
To put this information together in SQL, you must perform an operation called a join. This simply
means joining two or more tables together to follow the relationships between the data. For
example, if you want to see the orders that customer Julie Smith has placed, you will need to look
at the Customers table to find Julie’s CustomerID and then at the Orders table for orders with that
CustomerID.
Let’s begin by looking at some SQL for the query about Julie Smith we just discussed:
You achieve this result by placing a join condition in the WHERE clause. This special type of
conditional statement explains which attributes show the relationship between the two tables.
Customers.CustomerID = Orders.CustomerID
which tells MySQL to put rows in the result table only if the CustomerID from the Customers table
matches the CustomerID from the Orders table. By adding this join condition to the query, you
actually convert the join to a different type, called an equi-join.
Also notice the dot notation used to make it clear which table a particular column comes from; that
is, Customers.CustomerID refers to the CustomerID column from the Customers table, and
Orders.CustomerID refers to the CustomerID column from the Orders table. This dot notation is
required if the name of a column is ambiguous—that is, if it occurs in more than one table.
Joining more than two tables is no more difficult than a two-table join. As a general rule, you need
to join tables in pairs with join conditions. Think of it as following the relationships between the
data from table to table to table.
For example, if you want to know which customers have ordered books on Java, you need to trace
these relationships through quite a few tables.
You need to find customers who have placed at least one order that included an Order_Item that
is a book about Java. To get from the Customers table to the Orders table, you can use the
CustomerID as shown previously. To get from the Orders table to the Order_Items table, you can
use the OrderID. To get from the Order_Items table to the specific book in the Books table, you
can use the BookID. After making all those links, you can test for books with Java in the title and
return the names of customers who bought any of those books. Let’s look at a query that does all
those things:
SELECT Customers.Name
FROM Customers, Orders, Order_Items, Books
WHERE Customers.CustomerID = Orders.CustomerID
AND Orders.OrderID = Order_Items.OrderID
AND Order_Items.ISBN = Books.ISBN
AND Books.Title = “Java”;
If you want to display rows retrieved by a query in a particular order, you can use the ORDER BY
clause of the SELECT statement. This feature is handy for presenting output in a good human-
readable format.
The ORDER BY clause sorts the rows on one or more of the columns listed in the SELECT clause.
For example,
SELECT Name
FROM Customers
LIMIT 2;
In addition to retrieving data from the database, you often want to change it. For example, you
might want to increase the prices of books in the database. You can do this using an UPDATE
statement. The usual form of an UPDATE statement is
UPDATE tablename
SET column1=expression1[,column2=expression2,...]
[WHERE condition]
[ORDER BY order_criteria]
[LIMIT number]
The basic idea is to update the table called tablename, setting each of the columns named to the
appropriate expression. You can limit an UPDATE to particular rows with a WHERE clause and
limit the total number of rows to affect with a LIMIT clause. ORDER BY is usually used only in
conjunction with a LIMIT clause; for example, if you are going to update only the first 10 rows,
you want to put them in some kind of order first.
Let’s look at some examples. If you want to increase all the book prices by 10%, you can use an
UPDATE Customers
SET Address = '250 Olsens Road'
WHERE CustomerID = 4;
Altering table in MySQL
In addition to updating rows, you might want to alter the structure of the tables within your
database. For this purpose, you can use the flexible ALTER TABLE statement. The basic form of
this statement is
You may frequently realize that you haven’t made a particular column “big enough” for the data
it has to hold. For example, previously in the customers table, you allowed names to be 50
characters long. After you start getting some data, you might notice that some of the names are too
long and are being truncated. You can fix this problem by changing the data type of the column so
that it is 70 characters long instead:
Deleting rows from the database is simple. You can do this using the DELETE statement, which
generally looks like this:
if a particular customer hadn’t placed any orders for a long time and you wanted to do some
housekeeping:
Dropping Tables
At times, you may want to get rid of an entire table. You can do this with the DROP TABLE
statement. This process is simple, and it looks like this:
This query deletes all the rows in the table and the table itself, so be careful using it.
You can go even further and eliminate an entire database with the DROP DATABASE statement,
which looks like this:
This query deletes all the rows, all the tables, all the indexes, and the database itself, so it goes
without saying that you should be somewhat careful using this statement.
Notice
All the concepts that have been discussed above are from Database course. Use them to refresh your
Insights regarding to database manipulation. Database is a basic prerequisite for Backend development.
Try to maintain the Bookstore database for the remaining sessions on this chapter. Happy Coding 😊
In this chapter, we follow through with the bookstore application discussed in our class session.
As a reminder, here is the schema for the application (Bookstore):
Remember that each primary key is underlined and each foreign key is italic.
The basic PHP library for connecting to MySQL is called mysqli. The i stands for improved, as
there was an older library called mysql. When using the mysqli library in PHP, you can use either
an object-oriented or procedural syntax. For this course, we are going to use the structural
programming, and students can further cover the object oriented one.
The following function is used in the PHP script to connect to the MySQL database:
mysql_connect();
Example:
$servername = "localhost";
$username = "root";
$password = "";
$database = "bookstore";
// connect to the database
This function returns a resource rather than an object. This resource represents the connection to
the database, and if you are using the procedural approach, you will need to pass this resource in
to all the other mysqli functions.
After configuring and connecting to the MySQL database, you can start executing PHP commands
on the server. To actually perform the query to manipulate your database, you can use the
mysqli_query() function. Before doing this, however, it’s a good idea to set up the query you want
to run on a string varialble.
Inserting Data
Inserting data using PHP is identical to the procedure of data input using HTML pages. The
advantage of using PHP is that the script does not need to be changed for each new piece of input
data. Users can also input their own data on the web page.
Example:
if ($result) {
echo "Success";
}
else {
echo "Error executing query: " . mysqli_error($conn);
}
Displaying Data
To display (or output) the entered data using PHP, you can use the following MySQL command
with the result assigned to the variable.
Example:
// SQL query
$sql = "SELECT * FROM customers";
The result obtained from database is always in an object format, so a large variety of functions is
available to break the results out in different ways. In this example, we counted the number of
rows returned and also retrieved the individual values for each column in each row returned. We
have used a while loop to iterate on every row of our result since most of the fetch functions return
a single row from the obtained object. Meaning, in the loop, each time mysqli_fetch_assoc() is
called, it fetches the next result row and returns it as an associative array, which we named it as
row. Besides from mysqli_fetch_assoc() we can use mysqli_fetch_array(), which returns the next
row from the result set as an array, mysqli_fetch_all() returns all of the rows returned by the query
as an array of arrays, which is multidimensional array, or mysqli_fetch_object() returns the next
row from the result set as an object.
The other thing is that we can write any SQL statement and pass it to mysqli_query() function,
exactly like the above example, this works for all database statements including creating database
or table, creating constraints of a table, populating the table (insertion), updating the table, deleting
data, dropping column, or table, or even the database and so on. If the statement is not selection
then we only have to worry whether the statement is executed or not, and to do this we will chech
the returned result using conditional statement.
Example:
After executing our database operations we then have to close the established connection. This is
not necessary, but recommended practice. But in most cases PHP tries to close the connection
when the script finishes execution. Use mysqli_close() function to do this, passing your connection
variable created while you initially establish the connection.
Example:
mysqli_close($conn);
Controlling Access
In order to limit the audience in terms of users allowed to modify and read the data, you can set a
password to the created database. In terms of default settings, the host's username is "root" and
there no password is provided. Follow the given steps to increase the privacy of your database:
STEP 1- Click on the "User Accounts" tab at the top of the page.
STEP 2- Press "Edit Privileges" under "Actions" option corresponding the Username= "root" and
Hostname = "localhost".
STEP 3- Click on the tab 'Change password' and type your password in the provided field. Retype
the password to confirm it and then finally click on the "Go." Now the password has been set.
Besides from privileges and passwords you can export your current database and back it up as an
alternative way of security mechanism.
Here is my static message page try to render it in your mind. Don’t worry you don’t need a
server to run my message. Let your mind replace apache for today.
<html>
<head>
<style>
h1 {
color: #ff6600;
font-family: 'Arial', sans-serif;
text-align: center;
}
p{
color: #333333;
font-family: 'Roboto', sans-serif;
text-align: justify;
}
.highlight {
background-color: #ffff99;
padding: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Dear friends, students, and specifically the true ones I have invested in and proud to call
developers,</h1>
<p>As we come to the end of two consecutive course modules and months of lectures on website
development, I would like to take a moment to reflect on our journey together. It has been an
incredible experience witnessing your growth and progress as aspiring developers.</p>
<p>Throughout these modules and lecture hours, we have faced numerous challenges and
overcome them together. From the basics of HTML and CSS to the intricacies of JavaScript and
backend development, we have delved into the world of web engineering, exploring its vast
possibilities. Your dedication, hard work, and enthusiasm have been truly commendable.</p>
<p>I want to express my deepest appreciation and pride for each and every one of you. You have
shown a genuine passion for coding, and it has been an honor to be a part of your learning process.
From the first lines of code you wrote to the complex projects you completed, I have watched you
transform into skilled developers, ready to take on the digital world.</p>
<p>I would also like to share a reminder with all of you regarding the ups and downs you may
encounter on your coding journey. Whether you're just starting or have already gained some
experience, it's important to keep these points in mind:</p>
<ul>
<li>
Embrace the Challenges: Coding can be challenging, and it's natural to face difficulties along the
way. Don't be discouraged by the complexity of the tasks or the occasional roadblocks you
encounter. Instead, embrace these challenges as opportunities for growth and learning. Remember,
every problem you solve is a step forward in your coding skills.
</li>
<li>
Persistence and Resilience: Success in coding requires persistence and resilience. There will be
times when you feel stuck or frustrated, but it's important to keep pushing forward. Stay
determined, seek help from your peers or mentors, and be open to trying different approaches. The
ability to bounce back from setbacks is what sets successful developers apart.
</li>
<li>
Celebrate Your Successes: It's crucial to acknowledge and celebrate your achievements, no
matter how small they may seem. Each line of code you write, each bug you fix, and each feature
you implement is a testament to your progress. Take pride in your accomplishments and use them
as motivation to keep expanding your skills.
</li>
<p>
Remember, coding is not just about writing lines of code—it's about problem-solving, creativity,
and continuous learning. By mastering web engineering, you have the power to create remarkable
digital experiences that can make a difference in people's lives.
</p>
</div>
<blockquote>Web engineering is a journey of exploration, where code becomes the brush, and the
digital canvas awaits your creativity to bring ideas to life.<blockquote>
No matter where you are in your coding journey, keep exploring, keep learning, and keep pushing
your boundaries. The world of web development is constantly evolving, and your dedication and
passion will drive your success.</p>
<em>And I just wanted to write my message programmatically, just for fun, not for confusion.
Happy Coding Journey. 😊 </em>
<h2>Sincerely,</h2>
<p>Ephrem Tesfaye</p>
</body>
</html>