Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Ephrem Tesfaye - IP-II - Chapter-Seven

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

Internet Programming II Chapter Seven– PHP & MySQL Database

College of Engineering, Technology and Computational Sciences


Department of Computer Science

Course Title: Internet Programming II (COSC 3032)

Topic: MySQL Relational Database and PHP

Topic Contents

7. MySQL Relational Database and PHP


7.1 Introduction to MySQL DBMS
7.2 PHP-MySQL Database connectivity
7.3 PHP-MySQL Database Manipulation
7.4 Making your MySQL database secure

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

Compiled By: Ephrem Tesfaye Tsidu 1


Internet Programming II Chapter Seven– PHP & MySQL Database

Relational Database Concepts (Summary)

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.

Compiled By: Ephrem Tesfaye Tsidu 2


Internet Programming II Chapter Seven– PHP & MySQL Database

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.

OrderId CustomerID Amount Date


1 3 27.50 02-Apr-2007
2 1 12.99 15-Apr-2007
3 2 74.00 19-Apr-2007
4 3 6.99 01-May-2007

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

Compiled By: Ephrem Tesfaye Tsidu 3


Internet Programming II Chapter Seven– PHP & MySQL Database

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

Customers (CustomerID, Name, Address, City)

Orders (OrderID, CustomerID, Amount, Date)

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.

Compiled By: Ephrem Tesfaye Tsidu 4


Internet Programming II Chapter Seven– PHP & MySQL Database

Things to be considered during designing tour own database

 Think About the Real-World Objects You Are Modeling


 Avoid Storing Redundant Data (redundancy results insertion modification and deletion
anomalies)
 Use Atomic Column Values
 Choose Sensible Keys
 Think About What You Want to Ask the Database (think reports)

Activity

Refer to your database course material about those design issues

7.1 Introduction to MySQL DBMS

What is MySQL?

MySQL is an open-source relational database management system (RDBMS. Its name is a


combination of "My", the name of co-founder Michael Widenius's daughter My, and "SQL", the
acronym for Structured Query Language. A relational database organizes data into one or more
data tables in which data may be related to each other; these relations help structure the data. SQL
is a language that programmers use to create, modify and extract data from the relational database,
as well as control user access to the database. In addition to relational databases and SQL, an
RDBMS like MySQL works with an operating system to implement a relational database in a
computer's storage system, manages users, allows for network access and facilitates testing
database integrity and creation of backups.

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.

Compiled By: Ephrem Tesfaye Tsidu 5


Internet Programming II Chapter Seven– PHP & MySQL Database

MySQL and XAMPP

XAMPP stack of software is an open-source localhost server providing a number of functionalities


through the package of software it contains. The software, which is part of XAMPP is
started/stopped using the XAMPP Control Panel. It is used for testing the projects and
modifications offline before launching it on the global web. One such very important functionality
provided by XAMPP is the creation of the MySQL database. This is done by using phpMyAdmin.

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

Compiled By: Ephrem Tesfaye Tsidu 6


Internet Programming II Chapter Seven– PHP & MySQL Database

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

Creating and altering database in MySQL

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-

 The number of characters used should be equal to or less than 64.


 The name should comprise of letters, numbers and underscore.
 The DB name should not start with a number.
 It should be relevant to the topic for which it is being created.

Compiled By: Ephrem Tesfaye Tsidu 7


Internet Programming II Chapter Seven– PHP & MySQL Database

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:

CREATE DATABASE Bookstore;

Creating and altering tables in MySQL

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.

Compiled By: Ephrem Tesfaye Tsidu 8


Internet Programming II Chapter Seven– PHP & MySQL Database

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.

Compiled By: Ephrem Tesfaye Tsidu 9


Internet Programming II Chapter Seven– PHP & MySQL Database

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:

CREATE TABLE tableName(


Column1 DATA-TYPE NULL/NOT NULL,
Column2 DATA-TYPE NULL/NOT NULL,
Column3 DATA-TYPE NULL/NOT NULL,
Column4 DATA-TYPE NULL/NOT NULL
);
Creating and altering constraints in MySQL

You can create Primary and foreign key as follows

CREATE TABLE tableName(


Column1 DATA-TYPE NULL/NOT NULL PRIMARY KEY(if),
Column2 DATA-TYPE NULL/NOT NULL
Column3 DATA-TYPE NULL/NOT NULL
Column4 DATA-TYPE NULL/NOT NULL
);
Or another way

CREATE TABLE tableName(


Column1 DATA-TYPE NULL/NOT NULL,
Column2 DATA-TYPE NULL/NOT NULL,
Column3 DATA-TYPE NULL/NOT NULL,
Column4 DATA-TYPE NULL/NOT NULL,
PRIMARY KEY (Column1),
FOREIGN KEY (Column4) REFERENCES itsOriginalTableName(Column4,
);

Compiled By: Ephrem Tesfaye Tsidu 10


Internet Programming II Chapter Seven– PHP & MySQL Database

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:

CREATE TABLE tableName(


Column1 DATA-TYPE NULL/NOT NULL,
Column2 DATA-TYPE NULL/NOT NULL,
Column3 DATA-TYPE NULL/NOT NULL,
Column4 DATA-TYPE NULL/NOT NULL,
PRIMARY KEY (Column1, Column2),
FOREIGN KEY (Column3) REFERENCES itsOriginalTableName(Column3),
FOREIGN KEY (Column4) REFERENCES itsOriginalTableName(Column4)
);
Example: Customers table will be created just like this.

CREATE TABLE Customers


( CustomerID INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name CHAR(50) NOT NULL,
Address CHAR(100) not null,
City CHAR(30) not null
);

Activity

Based on the schema provided, create all the tables needed for our minimal Bookstore application

(From the practical session).

As a reminder, here is the schema for the application (Bookstore):

Customers (CustomerID, Name, Address, City)

Orders (OrderID, CustomerID, Amount, Date)

Books (BookID, Author, Title, Price)

Order_Items (OrderID, BookID, Quantity)

Compiled By: Ephrem Tesfaye Tsidu 11


Internet Programming II Chapter Seven– PHP & MySQL Database

Adding table entries in MySQL

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.

The most common form of an INSERT statement is

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

Compiled By: Ephrem Tesfaye Tsidu 12


Internet Programming II Chapter Seven– PHP & MySQL Database

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.

Selecting table entries in MySQL

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 Name, City


FROM Customers;
You can specify as many columns as you like from a table by listing them after the SELECT
keyword. You can also specify some other items. One useful item is the wildcard operator, *,
which matches all the columns in the specified table or tables. For example, to retrieve all columns
and all rows from the Order_Items table, you would use

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;

Compiled By: Ephrem Tesfaye Tsidu 13


Internet Programming II Chapter Seven– PHP & MySQL Database

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:

Operator Name Example Description


= Equality customerid = 3 Tests whether two values are
equal
> Greater than amount > 60.00 Tests whether one value is greater
than another
< Less than amount < 60.00 Tests whether one value is less
than another
>= Greater than amount >= Tests whether one value is greater
or equal to 60.00 than or equal to another

<= 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

IS NULL n/a address is Tests whether a field does not


null contain a value

BETWEEN n/a amount between Tests whether a value is greater


0 and 60.00 than or equal to a minimum
value and less than or equal to a
maximum value
IN n/a city in Tests whether a value is in a particular set
("Carlton",
"Moe")

Compiled By: Ephrem Tesfaye Tsidu 14


Internet Programming II Chapter Seven– PHP & MySQL Database

NOT IN n/a city not in Tests whether a value is not in


("Carlton", a set
"Moe")
LIKE Pattern name like Checks whether a value matches
match ("Fred %") a pattern using simple SQL
pattern matching
NOT LIKE Pattern name not like Checks whether a value doesn’t
match ("Fred %") match a pattern

REGEXP Regular name regexp Checks whether a value matches


expression a regular expression

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.

Compiled By: Ephrem Tesfaye Tsidu 15


Internet Programming II Chapter Seven– PHP & MySQL Database

Let’s begin by looking at some SQL for the query about Julie Smith we just discussed:

SELECT Orders.OrderID, Orders.Amount, Orders.Date


FROM Customers, Orders
WHERE Customers.Name = 'Julie Smith' and Customers.CustomerID = Orders.CustomerID;
By listing two tables, you also specify a type of join, possibly without knowing it. The comma
between the names of the tables is equivalent to typing INNER JOIN or CROSS JOIN. This is a
type of join sometimes also referred to as a full join, or the Cartesian product of the tables. It
means, “Take the tables listed, and make one big table. The big table should have a row for each
possible combination of rows from each of the tables listed, whether that makes sense or not.” In
other words, you get a table, which has every row from the customers table matched up with every
row from the Orders table, regardless of whether a particular customer placed a particular order.

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.

In this case, the join condition is

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.

Compiled By: Ephrem Tesfaye Tsidu 16


Internet Programming II Chapter Seven– PHP & MySQL Database

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, Address


FROM Customers
ORDER BY Name;
One clause of the SELECT statement that can be particularly useful in Web applications is LIMIT.
It is used to specify which rows from the output should be returned. This clause takes one or two
parameters. If you provide one parameter, it specifies the number of rows to be returned. For
example, the following query

SELECT Name
FROM Customers
LIMIT 2;

Compiled By: Ephrem Tesfaye Tsidu 17


Internet Programming II Chapter Seven– PHP & MySQL Database

Modifying table entries in MySQL

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 statement without a WHERE clause:


UPDATE Books
SET Price = Price * 1.1;
If, on the other hand, you want to change a single row—say, to update a customer’s address—you
can do it like this:

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

ALTER TABLE tablename alteration [, alteration ...]

Compiled By: Ephrem Tesfaye Tsidu 18


Internet Programming II Chapter Seven– PHP & MySQL Database

Let’s look at a few of the more common uses of ALTER TABLE.

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:

ALTER TABLE Customers


MODIFY Name CHAR(70) NOT NULL;
Another common occurrence is the need to add a column. Imagine that a sales tax on books is
introduced locally and that Book-O-Rama needs to add the amount of tax to the total order but
keep track of it separately. You can add a Tax column to the Orders table as follows:

ALTER TABLE Orders


ADD Tax FLOAT(6,2) AFTER Amount;
Getting rid of a column is another case that comes up frequently. You can delete the column you
just added as follows:

ALTER TABLE Orders


DROP Tax;
Deleting table entries in MySQL

Deleting rows from the database is simple. You can do this using the DELETE statement, which
generally looks like this:

DELETE FROM table


[WHERE condition]
[ORDER BY order_cols]
[LIMIT number]
If you write DELETE FROM table; on its own, all the rows in a table will be deleted, so be careful.
Usually, you want to delete specific rows, and you can specify the ones you want to delete with a
WHERE clause. You might do this, if, for example, a particular book were no longer available or

Compiled By: Ephrem Tesfaye Tsidu 19


Internet Programming II Chapter Seven– PHP & MySQL Database

if a particular customer hadn’t placed any orders for a long time and you wanted to do some
housekeeping:

DELETE FROM Customers


WHERE CustomerID=5;
The LIMIT clause can be used to limit the maximum number of rows that are actually deleted.
ORDER BY is usually used in conjunction with LIMIT

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:

DROP TABLE table;

This query deletes all the rows in the table and the table itself, so be careful using it.

Dropping a Whole Database

You can go even further and eliminate an entire database with the DROP DATABASE statement,
which looks like this:

DROP DATABASE database;

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 😊

Compiled By: Ephrem Tesfaye Tsidu 20


Internet Programming II Chapter Seven– PHP & MySQL Database

7.2 PHP-MySQL Database connectivity

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):

Customers (CustomerID, Name, Address, City)

Orders (OrderID, CustomerID, Amount, Date)

Books (BookID, Author, Title, Price)

Order_Items (OrderID, BookID, Quantity)

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();

Where the parameters to be passed are:

 The server address on which the web site is running,


 The user name for the database access
 The password for the database access
 The database name for the intended access

Example:

// put our database connection data on variables

$servername = "localhost";
$username = "root";
$password = "";
$database = "bookstore";
// connect to the database

Compiled By: Ephrem Tesfaye Tsidu 21


Internet Programming II Chapter Seven– PHP & MySQL Database

$conn = mysqli_connect($servername, $username, $password, $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.

7.3 PHP-MySQL Database Manipulation

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:

//accepting data from form fields


$un = $_POST['username'];
$pw = $_POST['password'];
$ad = $_POST['address'];
$pn = $_POST['phone'];

// SQL query preparation


$sql = "INSERT INTO Customers(Name, Address, PhoneNo, Password) VALUES('$un', '$ad',
'$pn', '$pw')";

// Execute the query


$result = mysqli_query($conn, $sql);

// Check if the query was successful

Compiled By: Ephrem Tesfaye Tsidu 22


Internet Programming II Chapter Seven– PHP & MySQL Database

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";

// Execute the query


$result = mysqli_query($conn, $sql);

// Check if the query was successful


if ($result) {

// Fetch the data


while ($row = mysqli_fetch_assoc($result)) {
// Process each row of data
// Access the column values using associative array keys
echo "ID: " . $row['CustomerId'] . ", Name: " . $row['Name'] . "Phone No: " .
$row['PhoneNo'] . "Address: " . $row['Address'] . "<br>";
}
} else {
echo "Error executing query: " . mysqli_error($conn);
}

Compiled By: Ephrem Tesfaye Tsidu 23


Internet Programming II Chapter Seven– PHP & MySQL Database

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:

// Execute the query


$result = mysqli_query($conn, $sql);

// Check if the query was successful


if ($result) {
echo "Success";
}
else {
echo "Error executing query: " . mysqli_error($conn);
}
But if the statement is selection then the next intended activity will go on, using the fetching
methods with or without loops.

Compiled By: Ephrem Tesfaye Tsidu 24


Internet Programming II Chapter Seven– PHP & MySQL Database

Disconnecting from the database

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);

7.4 Making your MySQL database secure

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".

Compiled By: Ephrem Tesfaye Tsidu 25


Internet Programming II Chapter Seven– PHP & MySQL Database

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.

_______________The End! _______________


………Message from your instructor… coming up on the next page =>

Compiled By: Ephrem Tesfaye Tsidu 26


Internet Programming II Chapter Seven– PHP & MySQL Database

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>

Compiled By: Ephrem Tesfaye Tsidu 27


Internet Programming II Chapter Seven– PHP & MySQL Database

<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>

<div class = “highlight” >

<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>

Compiled By: Ephrem Tesfaye Tsidu 28


Internet Programming II Chapter Seven– PHP & MySQL Database

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>

<p>In conclusion, I would like to leave you with this quote:

<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>

<b>Wishing you all the best in your future endeavors!</b><br/>

<h2>Sincerely,</h2>

<p>Ephrem Tesfaye</p>

<p>Website Development Instructor</p>

</body>

</html>

Compiled By: Ephrem Tesfaye Tsidu 29

You might also like