0% found this document useful (0 votes)
54 views34 pages

Week10 CM MDL CC225

Uploaded by

Edward Rodriguez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views34 pages

Week10 CM MDL CC225

Uploaded by

Edward Rodriguez
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ASIAN INSTITUTE OF COMPUTER STUDIES

Bachelor of Science in Computer Science


Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

MODULE 10: DATA INTEGRITY AND CONSTRAINTS


WEEK 10

Learning Outcomes:
After completing this course you are expected to demonstrate the following:
1. Explains the data integrity and constraints in SQL and its standard
standards. Elaborate the
triggers and active datab
databases
ases and further data definition commands.

A. Engage
Word Search
Instruction: Find the word in the puzzle.Words can go in any direction and can share letters
as they cross over each other. Write your answer on the space provided below.

Answers:
1.______________________
________________ 4.______________________ 7.______________________
2.______________________ 5.______________________ 8.______________________
3.______________________ 6.______________________ 9.______________________

B. Explore
Video Title: Data Integrity
Integrity– Week 10
YouTube Link: https://www.youtube.com/watch?v=1D_h
https://www.youtube.com/watch?v=1D_h-yFtQVo
yFtQVo
Module Video Filename: Module10 video – Data Integrity

C. Explain
In this era of big data, when more pieces of information are pro processed and stored
than ever, implementing measures that preserve the integrity of the data that’s collected is
increasingly important. Understanding the fundamentals of data integrity and how it works is
the first step in keeping data safe. Read on to lear
learnn what data integrity is, why it’s essential,
and what you can do to keep your data intact.
Data integrity is the overall accuracy, completeness, and consistency of data. Data
integrity also refers to the safety of data in regards to regulatory compliance and security. It
Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos,
Santos MSCS Page 1 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

is maintained by a collection of processes, rules, and standards implemented during the


design phase. When the integrity of data is secure, the information stored in a database will
remain complete, accurate, and reliable no matter how long it’s stored or how often it’s
accessed. Data integrity also ensures that your data is safe from any outside forces.
While data integrity is concerned with keeping information intact and accurate for the
entirety of its existence, the goal of data security is to protect information from outside
attacks. Data security is but one of the many facets of data integrity. Data security is not
broad enough to include the many processes necessary for keeping data unchanged over
time.
Much like data security, data quality is only a part of data integrity, but a crucial one.
Data integrity encompasses every aspect of data quality and goes further by implementing an
assortment of rules and processes that govern how data are entered, stored, transferred, and
much more.

D. Elaborate
It is important that data adhere to a predefined set of rules, as determined by the
database administrator or application developer. As an example of data integrity, consider the
tables employees and departments and the business rules for the information in each of the
tables, as illustrated in Figure 10.1.

Figure 10.1 Examples of Data Integrity

Note that some columns in each table have specific rules that constrain the data
contained within them.
Types of Data Integrity
This section describes the rules that can be applied to table columns to enforce different
types of data integrity.
 Null Rule - A null rule is a rule defined on a single column that allows or disallows inserts
or updates of rows containing a null (the absence of a value) in that column.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 2 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

 Unique Column Values - A unique value rule defined on a column (or set of columns)
allows the insert or update of a row only if it contains a unique value in that column (or
set of columns).
 Primary Key Values - A primary key value rule defined on a key (a column or set of
columns) specifies that each row in the table can be uniquely identified by the values in
the key.
 Referential Integrity Rules - A referential integrity rule is a rule defined on a key (a
column or set of columns) in one table that guarantees that the values in that key match
the values in a key in a related table (the referenced value).

Referential integrity also includes the rules that dictate what types of data manipulation
are allowed on referenced values and how these actions affect dependent values. The
rules associated with referential integrity are:

 Restrict: Disallows the update or deletion of referenced data.


 Set to Null: When referenced data is updated or deleted, all associated dependent
data is set to NULL.
 Set to Default: When referenced data is updated or deleted, all associated
dependent data is set to a default value.
 Cascade: When referenced data is updated, all associated dependent data is
correspondingly updated. When a referenced row is deleted, all associated
dependent rows are deleted.
 No Action: Disallows the update or deletion of referenced data. This differs
from RESTRICT in that it is checked at the end of the statement, or at the end of the
transaction if the constraint is deferred. (Oracle uses No Action as its default action.)

 Complex Integrity Checking - Complex integrity checking is a user-defined rule for a


column (or set of columns) that allows or disallows inserts, updates, or deletes of a row
based on the value it contains for the column (or set of columns).

Integrity Constraints
An integrity constraint is a declarative method of defining a rule for a column of a table.
1. NOT NULL Integrity Constraints
By default, all columns in a table allow nulls. Null means the absence of a value.
A NOT NULL constraint requires a column of a table contain no null values. For example, you
can define a NOT NULL constraint to require that a value be input in the last_name column for
every row of the employees table.Figure 10.2 illustrates a NOT NULL integrity constraint.

Figure 10.2 NOT NULL Integrity Constraints

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 3 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

2. UNIQUE Key Integrity Constraints


A UNIQUE key integrity constraint requires that every value in a column or set of
columns (key) be unique—that is, no two rows of a table have duplicate values in a specified
column or set of columns.
For example, in Figure 10.3 a UNIQUE key constraint is defined on the DNAME column of
the dept table to disallow rows with duplicate department names.

Figure 10.3 A UNIQUE Key Constraint


Unique Keys
The columns included in the definition of the UNIQUE key constraint are called the unique
key. Unique key is often incorrectly used as a synonym for the terms UNIQUE key
constraint or UNIQUE index. However, note that key refers only to the column or set of
columns used in the definition of the integrity constraint.
If the UNIQUE key consists of more than one column, then that group of columns is said to be
a composite unique key. For example, in Figure 10.4 the customer table has a UNIQUE key
constraint defined on the composite unique key: the area and phone columns.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 4 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Figure 10.4 A Composite UNIQUE Key Constraint


This UNIQUE key constraint lets you enter an area code and telephone number any
number of times, but the combination of a given area code and given telephone number cannot
be duplicated in the table. This eliminates unintentional duplication of a telephone number.

UNIQUE Key Constraints and Indexes


Oracle enforces unique integrity constraints with indexes. For example, in Figure 10.4, it
enforces the UNIQUE key constraint by implicitly creating a unique index on the composite
unique key. Therefore, composite UNIQUE key constraints have the same limitations imposed
on composite indexes: up to 32 columns can constitute a composite unique key.
If a usable index exists when a unique key constraint is created, the constraint uses that
index rather than implicitly creating a new one.

3. PRIMARY KEY Integrity Constraints


Each table in the database can have at most one PRIMARY KEY constraint. The values
in the group of one or more columns subject to this constraint constitute the unique identifier
of the row. In effect, each row is named by its primary key values.
The implementation of the PRIMARY KEY integrity constraint guarantees that both of
the following are true:
 No two rows of a table have duplicate values in the specified column or set of columns.
 The primary key columns do not allow nulls. That is, a value must exist for the primary
key columns in each row.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 5 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Primary Keys
The columns included in the definition of a table's PRIMARY KEY integrity constraint
are called the primary key. Although it is not required, every table should have a primary key so
that:
 Each row in the table can be uniquely identified
 No duplicate rows exist in the table
Figure 10.5 illustrates a PRIMARY KEY constraint in the dept table and examples of
rows that violate the constraint.

Figure 10.5 A Primary Key Constraint

4. Referential Integrity Constraints


Different tables in a relational database can be related by common columns, and the
rules that govern the relationship of the columns must be maintained. Referential integrity
rules guarantee that these relationships are preserved.
The following terms are associated with referential integrity constraints.
Term Definition
The column or set of columns included in the definition of
Foreign key the referential integrity constraint that reference a
referenced key.
The unique key or primary key of the same or different
Referenced key
table that is referenced by a foreign key.
The table that includes the foreign key. Therefore, it is the
Dependent or child table table that is dependent on the values present in the
referenced unique or primary key.
The table that is referenced by the child table's foreign key.
Referenced or parent table It is this table's referenced key that determines whether
specific inserts or updates are allowed in the child table.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 6 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

A referential integrity constraint requires that for each row of a table, the value in the
foreign key matches a value in a parent key.
Figure 10.6 shows a foreign key defined on the deptno column of the emp table. It
guarantees that every value in this column must match a value in the primary key of
the dept table (also the deptno column). Therefore, no erroneous department numbers can
exist in the deptno column of the emp table.
Foreign keys can be defined as multiple columns. However, a composite foreign key
must reference a composite primary or unique key with the same number of columns and the
same datatypes. Because composite primary and unique keys are limited to 32 columns, a
composite foreign key is also limited to 32 columns.

Figure 10.6 Referential Integrity Constraints

5. Self-Referential Integrity Constraints


Another type of referential integrity constraint, shown in Figure 10.7, is called a self-
referential integrity constraint. This type of foreign key references a parent key in the same
table.
In Figure 10.7, the referential integrity constraint ensures that every value in
the mgr column of the emp table corresponds to a value that currently exists in
the empno column of the same table, but not necessarily in the same row, because every
manager must also be an employee. This integrity constraint eliminates the possibility of
erroneous employee numbers in the mgr column.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 7 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Figure 10.7 Single Table Referential Constraints

6. CHECK Integrity Constraints


A CHECKintegrity constraint on a column or set of columns requires that a specified
condition be true or unknown for every row of the table. If a DML statement results in the
condition of the CHECKconstraint evaluating to false, then the statement is rolled back.

The Check Condition


CHECKconstraints let you enforce very specific integrity rules by specifying a check
condition. The condition of a CHECKconstraint has some limitations:
 It must be a Boolean expression evaluated using the values in the row being inserted or
updated, and
 It cannot contain subqueries; sequences; the SQL functions SYSDATE, UID, USER,
or USERENV; or the pseudocolumns LEVEL or ROWNUM.
In evaluating CHECKconstraints that contain string literals or SQL functions with
globalization support parameters as arguments (such as TO_CHAR, TO_DATE, and TO_NUMBER),
Oracle uses the database globalization support settings by default. You can override the
defaults by specifying globalization support parameters explicitly in such functions within
the CHECK constraint definition.

Multiple CHECK Constraints


A single column can have multiple CHECK constraints that reference the column in its
definition. There is no limit to the number of CHECK constraints that you can define on a
column.
If you create multiple CHECK constraints for a column, design them carefully so their
purposes do not conflict. Do not assume any particular order of evaluation of the conditions.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 8 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

The Mechanisms of Constraint Checking


To know what types of actions are permitted when constraints are present, it is useful
to understand when Oracle actually performs the checking of constraints. Assume the
following:
 The emp table has been defined as in Figure 10.7.
 The self-referential constraint makes the entries in the mgr column dependent on the
values of the empno column. For simplicity, the rest of this discussion addresses only
the empno and mgr columns of the emp table.

Consider the insertion of the first row into the emp table. No rows currently exist, so
how can a row be entered if the value in the mgr column cannot reference any existing value in
the empno column? Three possibilities for doing this are:
 A null can be entered for the mgr column of the first row, assuming that the mgr column
does not have a NOT NULL constraint defined on it. Because nulls are allowed in
foreign keys, this row is inserted successfully into the table.
 The same value can be entered in both the empno and mgr columns. This case reveals
that Oracle performs its constraint checking after the statement has been completely
run. To allow a row to be entered with the same values in the parent key and the
foreign key, Oracle must first run the statement (that is, insert the new row) and then
check to see if any row in the table has an empno that corresponds to the new
row's mgr.
 A multiple row INSERT statement, such as an INSERT statement with
nested SELECT statement, can insert rows that reference one another. For example,
the first row might have empno as 200 and mgr as 300, while the second row might
have empno as 300 and mgr as 200.

This case also shows that constraint checking is deferred until the complete execution of
the statement. All rows are inserted first, then all rows are checked for constraint
violations. You can also defer the checking of constraints until the end of
the transaction.

Consider the same self-referential integrity constraint in this scenario. The company has
been sold. Because of this sale, all employee numbers must be updated to be the current value
plus 5000 to coordinate with the new company's employee numbers. Because manager
numbers are really employee numbers, these values must also increase by 5000.

Figure 10.10 The EMP Table Before Updates


UPDATE employees
SET employee_id = employee_id + 5000,
manager_id = manager_id + 5000;

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 9 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Even though a constraint is defined to verify that each mgr value matches
an empno value, this statement is legal because Oracle effectively performs its constraint
checking after the statement completes. Figure 10.11 shows that Oracle performs the actions
of the entire SQL statement before any constraints are checked.

Figure 10.11 Constraint Checking


The examples in this section illustrate the constraint checking mechanism
during INSERT and UPDATE statements. The same mechanism is used for all types of DML
statements, including UPDATE, INSERT, and DELETE statements.
The examples also used self-referential integrity constraints to illustrate the checking
mechanism. The same mechanism is used for all types of constraints, including the following:
 NOT NULL
 UNIQUE key
 PRIMARY KEY
 All types of FOREIGN KEY constraints
 CHECK constraints

Triggers and Active Databases


Business rules are kind of reactive constraints in the form of whenever events
do action with a specification of what to do if certain event happens. The event is a request for
the execution of some database operation such as delete or insert a row. The action is a
statement of what needs to be done when the triggers is fired. A trigger may contain a pre-
condition that must be evaluated to true in order to execute the trigger.
The example codes are written in T-SQL for Microsoft SQL Server and PL/SQL for Oracle
Database and they are an illustrative implementation of one audit application, which records all
the changes associated to one table in the Database System.

Trigger execution:
There are mainly two types of triggers supported by the SQL standard the before and after
triggers although some vendors also support the instead of trigger.
 The after trigger is executed automatically after the statement that fires the trigger
completes but before the transaction is committed or rolled back.
 The before trigger is executed automatically first and then allows the requested action
on the database object to occur.
 The instead of trigger is executed automatically in place of the triggering action.
In SQL Server 2005 we can find the after and instead of triggers; the after trigger is
associated only to tables.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 10 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

In Oracle Database we can find before and after triggers and instead of
triggers associated only to views.

Trigger granularity:
There are two types of trigger granularity:
1. Row-level and
2. Statement-level granularity.

The row-level granularity assumes that a change to single row is an event, and changes
to several rows are view as separate events, thus, this kind of trigger is execute multiple times
and might know the old and new value of the affected row.

On the other hand, the statement-level granularity fires once for the whole statement such as
insert, delete and update and not for individual rows.

Triggers in Microsoft SQL Server 2000/2005


The SQL statement for the creation of trigger is shown in Listing 1:

Listing 1: The SQL statement syntax for the trigger creation in Microsoft SQL Server:

It is remarkable to say that Microsoft SQL Server creates two virtual table
named deleted and inserted to store the changes. These virtual tables not always have values
and depend on the requested operation. When the operation is update the deleted table has
the old values and the inserted table has the new ones. When the operation is insert, then
the inserted table has the inserted or new values and the deleted table is empty. And finally, if
the operation is delete, then the inserted table is empty and the deleted table has the deleted
or old values.
When a trigger is fired, you can determine which columns have been modified by using
the update function which returns true if an insert or update operation has occurred against
the columns, otherwise it returns false.
As part of the new features of Microsoft SQL Server 2005, now you can define triggers
which respond to server events for example for auditing when a table is created or dropped.
Let's illustrate the concepts using the proposed audit application. We're going to use the
AdventureWorks database shipped with the installation of Microsoft SQL Server 2005.
First of all, we're going to illustrate the after trigger.
Let's create a table to store the audits for the modifications to the
Purchasing.ShipMethod table using the entity identifier (ShipMethodID) and ship name (Name)
from this base table as well as three new fields for storing the modification date, kind of
operation (insert, update, delete) and who does the changes. Finally create the after

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 11 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

trigger, which is fired when one modification operation occurs. The underlying SQL code is
illustrated in Listing 2.

Listing 2: Create the audit table and trigger associated to Purchasing,ShipMethod table.

Now let's execute some database operations on the table Purchasing.ShipMethod and
finally look at the audits.

Listing 3: Execution of operations and examination of audit results.

Now let's demonstrate the use of instead of trigger which is allowed for both tables and
views, although the main use is to handle data modifications to views which do not allow data
modifications or the modification is unambiguous.
Assume that you want to select all the ship methods and the associated purchase
orders. In order to achieve this purpose, we create a view as shown in Listing 4.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 12 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Listing 4: Creation of the view


If you try to update the previous view, you receive an error message warning that the view is
not updateable because the modifications affect multiple base tables.
Finally let's code an instead of trigger to insert an audit row when the user tries to insert a row
on the view Purchasing.v_ShipMethodWithAudit.

Listing 5: The creation of the instead of trigger

Now when you try to insert a row into the view v_ShipMethodByOrder and audit error is
inserted into the table Purchasing.ShipMethodAudit as shown in Listing 6.

Listing 6: Trying to insert a row into the view

And finally, we're going to illustrate how to enforce rules such as the cancelation of forbidden
transactions. Let's suppose that we have a business rules that dictates not to delete any error
audit as shown in Listing 7.

Listing 7:
Now, let's try to delete the error audits as shown in Listing 8.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 13 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Listing 8:
When you try to execute the transaction, you receive you receive a message from the database
system as shown in Listing 9.

Listing 9: Aborted transaction's message received from the database system


Triggers in Oracle Database

The SQL statement for the creation of trigger is shown in Listing 10:

Listing 10: The SQL statement syntax for the trigger creation in Oracle Database.

There are some considerations concerning this syntax.


If for each option is specified, the trigger is row-level, otherwise it is statement level.
The special variables new and old are available to refer new and old values of data items. It is
like the virtual tables inserted and deleted in SQL Server. In the trigger body, these variables are
preceded by a colon, but in the when condition they do not have to be preceded by the colon.
The referencing clause can be used to assign aliases to the variables new and old.
The when clause enclosed in parentheses is a condition that must be satisfied in order to fire
the trigger.
Let's illustrate the concepts in Oracle database using the same audit application. We're going to
use the default Oracle database shipped with the installation of the product and the emp table
within the scott schema which stores facts about the employee business entity.
First of all, we're going to illustrate the after trigger.
Let's create a table to store the audits for the modifications to the emp table using the entity
identifier (empno) and name (ename) from this base table as well as three new fields for
storing the modification date, kind of operation (insert, update, delete) and who does the
changes as shown in Listing 11.

Listing 11: Creation of the table emp_audit

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 14 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Now, we're going to see how to use and create a before trigger. Because the table emp_audit
has a surrogate key as primary key, we need to create a sequence and associate the sequence
values to new rows. We want to do it automatically the same as Microsoft SQL Server 2005's
identity approach.
To implement this logic, we need to create a sequence object and then create a before
trigger as shown in Listing 12.

Listing 12: Implementation of the surrogate values

Now, let's test the code adding an insert employee audit as shown in Listing 13.

Listing 13: Testing the code

The output is shown in Listing 14.

Listing 14:
Now we're going to create the after trigger which is fired when any modification operation
occurs (insert, delete, update) and logs the underlying operation, the date and the responsible
as shown in Listing 15.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 15 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Listing 15: The after trigger logging any modification to the emp table.

Now, we test the code with the following case as shown in Listing 16.

Listing 16:

And the output is shown in Listing 17.

Listing 17:
And finally, let's demonstrate how to enforce integrity constraints using customs triggers as
shown in Listing 18.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 16 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Listing 18:

Now, let's attempt to insert a row with a negative salary as shown in Listing 19.

Listing 19:

And the output is shown in Listing 20.

Listing 20: Output

Data Control – Database Security


Database security refers to the range of tools, controls, and measures designed to establish and
preserve database confidentiality, integrity, and availability. This article will focus primarily on
confidentiality since it’s the element that’s compromised in most data breaches.
Database security must address and protect the following:
 The data in the database
 The database management system (DBMS)
 Any associated applications
 The physical database server and/or the virtual database server and the underlying
hardware
 The computing and/or network infrastructure used to access the database
Database security is a complex and challenging endeavor that involves all aspects of
information security technologies and practices. It’s also naturally at odds with database
usability. The more accessible and usable the database, the more vulnerable it is to security
threats; the more invulnerable the database is to threats, the more difficult it is to access and
use. (This paradox is sometimes referred to as Anderson’s Rule.)
By definition, a data breach is a failure to maintain the confidentiality of data in a database.
How much harm a data breach inflicts on your enterprise depends on a number of
consequences or factors:
 Compromised intellectual property: Your intellectual property—trade secrets,
inventions, proprietary practices—may be critical to your ability to maintain a
Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 17 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

competitive advantage in your market. If that intellectual property is stolen or exposed,


your competitive advantage may be difficult or impossible to maintain or recover.
 Damage to brand reputation: Customers or partners may be unwilling to buy your
products or services (or do business with your company) if they don’t feel they can trust
you to protect your data or theirs. A 2018 IBM-sponsored Harris Poll survey of adults
aged 18+ revealed that 63% rate quality of data protection against cyberattacks as
“extremely important” in their decision to purchase from a company.
 Business continuity (or lack thereof): Some business cannot continue to operate until a
breach is resolved.
 Fines or penalties for non-compliance: The financial impact for failing to comply with
global regulations such as the Sarbannes-Oxley Act (SAO) or Payment Card Industry Data
Security Standard (PCI DSS), industry-specific data privacy regulations such as HIPAA, or
regional data privacy regulations, such as Europe’s General Data Protection Regulation
(GDPR) can be devastating, with fines in the worst cases exceeding several million
dollars per violation.
 Costs of repairing breaches and notifying customers: In addition to the cost of
communicating a breach to customer, a breached organization must pay for forensic
and investigative activities, crisis management, triage, repair of the affected systems,
and more.

The following are the main control measures are used to provide security of data in databases:
1. Authentication:
Authentication is the process of confirmation that whether the user log in only according to
the rights provided to him to perform the activities of data base. A particular user can login
only up to his privilege, but he can’t access the other sensitive data. The privilege of
accessing sensitive data is restricted by using Authentication.

By using these authentication tools for biometrics such as retina and figure prints can
prevent the data base from unauthorized/malicious users.

2. Access Control:
The security mechanism of DBMS must include some provisions for restricting access to the
data base by unauthorized users. Access control is done by creating user accounts and to
control login process by the DBMS. So, that database access of sensitive data is possible
only to those people (database users) who are allowed to access such data and to restrict
access to unauthorized persons.

The database system must also keep the track of all operations performed by certain user
throughout the entire login time.

3. Inference Control:
This method is known as the countermeasures to statistical database security problem. It is
used to prevent the user from completing any inference channel. This method protects the
sensitive information from indirect disclosure.

Inferences are of two types, identity disclosure or attribute disclosure.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 18 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

4. Flow Control:
This prevents information from flowing in a way that it reaches unauthorized users.
Channels are the pathways for information to flow implicitly in ways that violate the privacy
policy of a company are called covert channels.

5. Database Security applying Statistical Method


Method:
Statistical database security focuses on the protection of confidential individual values
stored in and used for statistical purposes and used to retr
retrieve the summaries of values
based on categories. They do not permit to retrieve the individual information.

This allows to access the database to get statistical information about the number of
employees in the company but not to access the detailed confi
confidential/personal information
about specific individual employee.

6. Encryption:
This method is mainly used to protect sensitive data (such as credit card numbers, OTP
numbers) and other sensitive numbers. The data is encoded using some encoding
algorithms.

An unauthorized user who tries to access this encoded data will face difficulty in decoding
it, but authorized users are given decoding keys to decode data.
Table 10.0 Data Definition Commands

Data definition commands are used to create, modify and remove database objects such as
schemas, tables, views, indexes etc.Common Data Definition commands −

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos,
Santos MSCS Page 19 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Create
The main use of create command is to create a new table in database. It has a predefined
syntax in which we specify the columns and their respective data types.
CREATE TABLE <TABLE NAME>
( <COLUMN NAME> <DATA TYPE>,
<COLUMN NAME> <DATA TYPE>,
<COLUMN NAME> <DATA TYPE>,
<COLUMN NAME> <DATA TYPE>
);

Example :Create a student table with columns student name and roll number.
CREATE TABLE STUDENT
(STUDENT_NAME VARCHAR(30),
ROLL_NUMBER INT
);

Alter
An existing database object can be modified using the alter command. Alter command can do
following changes to any table-

 Add new columns.


 Add new integrity constraints.
 Modify existing columns.
 Drop integrity constraints.
General Syntax of the ALTER command is mentioned below −

For adding a new column


ALTER TABLE <table_name> ADD <column_name>

For renaming a table


ALTER TABLE <table_name> RENAME To <new_table_name>

For modifying a column


ALTER TABLE <table_name> MODIFY <column_name><data type >

For deleting a column


ALTER TABLE <table_name> DROP COLUMN <column_name>

Drop
This command can delete an index, table or view. Basically, any component from a relational
database management system can be removed using the Drop command. Once the object is
dropped, it cannot be reused.The general syntax of drop command is as follows −
DROP TABLE <table_name>;
DROP DATABASE <database_name>;

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 20 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

DROP TABLE <index_name>;

Truncate
Using the truncate command, all the records in a database are deleted, but the database
structure is maintained.
TRUNCATE TABLE <table name>

Comment
This command is used to add comments to the data dictionary.

 Single line comments: use ‘ --‘ before any text.


 Multiline comments: /* comments in between */

Rename
The rename command renames an object
Rename <old name> to <new name>

A brief history of SQL standards


The relational database model was slowly but surely becoming the industry standard in
the late 1980s. The problem was, even though SQL became a commonly recognized database
language, the differences in major vendors' implementations were growing, and some kind of
standard became necessary.

Around 1978, the Committee on Data Systems and Language (CODASYL) commissioned
the development of a network data model as a prototype for any future database
implementations. This continued work started in the early 1970s with the Data Definition
Language Committee (DDLC). By 1982, these efforts culminated in the data definition language
(DDL) and data manipulation language (DML) standards proposal. They became standards four
years later — endorsed by an organization with an improbably long name, the American
National Standards Institute National Committee on Information Technology Standards H2
Technical Committee on Database (ANSI NCITS H2 TCD).

NCITS H2 was given a mandate to standardize relational data model in 1982. The project
initially was based on IBM SQL/DS specifications, and for some time followed closely IBM DB2
developments. In 1984, the standard was redesigned to be more generic, to allow for more
diversity among database products vendors. After passing through all the bureaucratic loops it
was endorsed as an American National Standards Institute in 1986. The International Standard
Organization (ISO) adopted the standard in 1987. The revised standard, commonly known as
SQL89, was published two years later.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 21 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

SQL89 (SQL1)
SQL89 (or SQL1) is a rather worthless standard that was established by encircling all
RDBMS in existence in 1989. The major commercial vendors could not (and still to certain
degree cannot) agree upon implementation details, so much of the SQL89 standard is
intentionally left incomplete, and numerous features are marked as implementer-defined.

SQL92 (SQL2)
Because of the aforesaid, the previous standard had been revised, and in 1992 the first
solid SQL standard, SQL92 or SQL2, was published. ANSI took SQL89 as a basis, but corrected
several weaknesses in it, filled many gaps in the old standard, and presented conceptual SQL
features, which at that time exceeded the capabilities of any existing RDBMS
implementation.Also, the SQL92 standard is over five times longer than its predecessor (about
600 pages more), and has three levels of conformance.

Entry-level conformance is basically improved SQL89. The differences were insignificant


— for example, circular views and correlated subqueries became prohibited in SQL92

Intermediate-level conformance was a set of major improvements, including, but not


limited to, user naming of constraints; support for varying-length characters and national
character sets, case and cast expressions, built-in join operators, and dynamic SQL; ability to
alter tables, to set transactions, to use subqueries in updatable views, and use set operators
(UNION, EXCEPT, INTERSECT) to combine multiple queries' results.

Full-level conformance included some truly advanced features, including deferrable


constraints, assertions, temporary local tables, privileges on character sets and domains, and so
on.

The conformance testing was performed by the U.S. Government Department of


Commerce's National Institute of Standards and Technology (NIST). The vendors hurried to
comply because a public law passed in the beginning of the 1990s required an RDBMS product
to pass the tests in order to be considered by a federal agency.

In 1996, NIST dismantled the conformance testing program (citing "high costs" as the
reason behind the decision). Since then, the only verification of SQL standards compliance
comes from the RDBMS vendors themselves; this understandably increased the number of
vendor-specific features as well as nonstandard implementation of the standard ones. By 2001,
the original number of RDBMS vendors belonging to the ANSI NCIT had shrunk from 18 (at the
beginning of the 1990s) to just 7, though some new companies came aboard.

SQL99 (SQL3)
SQL3 represents the next step in SQL standards development. The efforts to define this
standard began virtually at the same time when its predecessor — SQL92 (SQL2) — was
adopted. The new standard was developed under guidance of both ANSI and ISO committees,
and the change introduced into the database world by SQL3 was as dramatic a shift from
nonrelational to relational database model; its sheer complexity is reflected in the number of

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 22 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

pages describing the standard — over 1,500 — comparing to 120 or so pages for SQL89 and
about 600 pages for SQL92. Some of the defined standards (for example, stored procedures)
existed as vendor-specific extensions, some of them (like OOP) are completely new to SQL
proper. SQL3 was released as an ANSI/ISO draft standard in 1999; later the same year its status
was changed to a standard level.

SQL3 extends traditional relational data models to incorporate objects and complex
data types within the relational tables, along with all supporting mechanisms. It brings into SQL
all the major OOP principles, namely inheritance, encapsulation, and polymorphism, all of
which are beyond the scope of this book, in addition to "standard" SQL features defined in
SQL92. It provides seamless integration with the data consumer applications designed and
implemented in OO languages (SmallTalk, Eiffel, etc.).

There are several commercial implementations of OODBMS on the market as well as OO


extensions to existing commercial database products; not all of them adhere to the standards
and a number of proprietary "features" makes them incompatible. For a time being OODBMS
(OORDBMS) occupy an insignificant portion of the database market, and the judgment is still
out there.

While it is impossible to predict what model will emerge as a winner in the future, it
seems reasonable to assume that relational databases are here in for a long haul and have not
yet reached their potential; SQL as the language of the RDBMS will keep its importance in the
database world.

Summary:

 Data integrity is the overall accuracy, completeness, and consistency of data. It also
refers to the safety of data in regards to regulatory compliance and security. It is
maintained by a collection of processes, rules, and standards implemented during the
design phase.
 Data security is but one of the many facets of data integrity. Data security is not broad
enough to include the many processes necessary for keeping data unchanged over time.
 Integrity constraint is a declarative method of defining a rule for a column of a table.
Not Null, Unique Key, Primary Key Referential, Self-Referential and Check are the types
of integrity constraints.
 After passing through all the bureaucratic loops SQL was endorsed as an American
National Standards Institute in 1986. The International Standard Organization (ISO)
adopted the standard in 1987.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 23 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

E. Evaluate
ASSESSMENT:
Instruction: Answer the questions below. Write your answer in the Answer Sheet (AS)
provided for 2 points each.

Identification.

_________________1. Creates an index for table.


_________________2. Creates a database schema.
_________________3. Defines a default value for a column.
_________________4. Permanently deletes a view
_________________5. Defines a primary key for a table

Review Question/S:
1. Explain the 3 standards of SQL.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 24 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

Hands-On Activity 10.1


 The Registration Page and Undesirable Characters

Figure 10.1. The registration page with its new header

Listing 10.1. Creating the Amended Registration Page (register-page.php)


<!doctype html>
<html lang=en>
<head>
<title>Register page</title>
<meta charset=utf-8><!--important prerequisite for escaping problem
characters-->
<link rel="stylesheet" type="text/css" href="includes.css">
</head>
<body>
<div id="container">
<!--Use the revised header-->
<?php include("register-header.php"); ?>
<?php include("nav.php"); ?>
<?php include("info-col.php"); ?>
<div id="content"><!-- Registration handler content starts here -->
<p>
<?php
// The link to the database is moved to the top of the PHP code.
require ('mysqli_connect.php'); // Connect to the db.
// This query INSERTs a record in the users table.
// Has the form been submitted?
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array(); // Initialize an error array.
// Check for a first name:
if (empty($_POST['fname'])) {
$errors[] = 'You forgot to enter your first name.';
} else {
$fn = mysqli_real_escape_string($dbcon, trim($_POST['fname']));

}
// Check for a last name
if (empty($_POST['lname'])) {
$errors[] = 'You forgot to enter your last name.';
} else {
$ln = mysqli_real_escape_string($dbcon, trim($_POST['lname']));
}
// Check for an email address
Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 25 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

if (empty($_POST['email'])) {
$errors[] = 'You forgot to enter your email address.';
} else {
$e = mysqli_real_escape_string($dbcon, trim($_POST['email']));
}
// Check for a password and match it against the confirmed password
if (!empty($_POST['psword1'])) {
if ($_POST['psword1'] != $_POST['psword2']) {
$errors[] = 'Your two passwords did not match.';
} else {
$p = mysqli_real_escape_string($dbcon, trim($_POST['psword1']));
}
} else {
$errors[] = 'You forgot to enter your password.';
}
if (empty($errors)) { // If it runs
// Register the user in the database...
// Make the query:
$q = "INSERT INTO users (user_id, fname, lname, email, psword,
registration_date)

VALUES (' ', '$fn', '$ln', '$e', SHA1('$p'), NOW() )";


$result = @mysqli_query ($dbcon, $q); // Run the query.
if ($result) { // If it runs
header ("location: register-thanks.php");
exit();
} else { // If it did not run
// Message:
echo '<h2>System Error</h2>
<p class="error">You could not be registered due to a system error. We
apologize
for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbcon) . '<br><br>Query: ' . $q .
'</p>';
} // End of if ($result)
mysqli_close($dbcon); // Close the database connection.
// Include the footer and quit the script:
include ('footer.php');
exit();
} else { // Report the errors.
echo '<h2>Error!</h2>
<p class="error">The following error(s) occurred:<br>';
foreach ($errors as $msg) { // Extract the errors from the array
and echo them
echo " - $msg<br>\n";

}
echo '</p><h3>Please try again.</h3><p><br></p>';
}// End of if (empty($errors))
} // End of the main Submit conditional.
?>
<h2>Register</h2>
<form action="register-page.php" method="post">
<p><label class="label" for="fname">First Name:</label>
<input id="fname" type="text" name="fname" size="30"
maxlength="30"
value="<?php if (isset($_POST['fname'])) echo $_POST['fname']; ?>"></p>

<p><label class="label" for="lname">Last Name:</label>


<input id="lname" type="text" name="lname" size="30" maxlength="40"
value="<?php if (isset($_POST['lname'])) echo $_POST['lname']; ?>"></p>

<p><label class="label" for="email">Email Address:</label>


Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 26 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

<input id="email" type="text" name="email" size="30" maxlength="60"


value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" ></p>

<p><label class="label" for="psword1">Password:</label>


<input id="psword1" type="password" name="psword1" size="12" maxlength="12"
value="<?php if (isset($_POST['psword1'])) echo $_POST['psword1']; ?>"
>&nbsp;
Between 8 and 12 characters.</p>

<p><label class="label" for="psword2">Confirm Password:</label>


<input id="psword2" type="password" name="psword2" size="12" maxlength="12"

value="<?php if (isset($_POST['psword2'])) echo $_POST['psword2']; ?>"


></p>

<p><input id="submit" type="submit" name="submit" value="Register"></p>


</form>
<?php include ('footer.php'); ?>
</p>
</div>
</div>
</body>
</html>

 Register Some Members

Table 10.1. Register Some Members

To maintain the security of private pages, we use a device called sessions. A session is a
server-side store of information about a user. It is deleted when a user exits a site, or it times-
out after a period (typically 20 minutes) that is set by the server administrator. A session checks
the credentials of users before allowing them to access a page.

Differentiating Between Two Types of Membership


The simpleIdb database in the previous chapter had a security problem; any non-
registered user could view the table of members by simply accessing the web site. We will now
ensure that the table of members can be viewed only by the developer and the membership
secretary (the administrator) and not by the whole world.

The solution will be to restrict access to the view_table.php page and all other
administrator pages so that only the membership secretary is allowed to view them. This will be
achieved by using sessions and a different user_level number for the administrator. The
Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 27 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

administrator will be provided with a user-friendly interface so that he can search and amend
membership records.

To sum up, our rules for differentiating between types of membership will be as follows:

• Non-members will not be able to view private pages because users can’t log in until they
are registered.
• Registered members will be able to access members’ pages because they can log in.
Doing so, initiates a session that allows them to open members’ pages.
• The administrator is the only person able to access administration pages. When he logs
in, the act of logging in starts a session that checks his user_level before he can open an
administrator’s page. His user_level is different from ordinary members’ user levels.

Before designing a login page, we must also create a means of differentiating between
an ordinary registered member and a member who is also the administrator. The administrator
will have extra privileges. In the next tutorial, you will learn how to add a new column with the
title user_level to an existing database table. This new column will enable us to differentiate
between types of membership.

 Create User Levels to Limit Access to Private Pages

To limit access to the view table page, we will add a column to the users table called
user_level. In this column, we will give the administrator a user level number 1. That number
relates to the membership secretary’s login details and to no other person.

Access phpMyAdmin, and click the database logindb. Then click the users table. Click the
Structure tab. Look below the records to find the item Add one column. The next steps are
illustrated in Figure 3-6.

Figure 10.2. The Add symbol (circled) can be seen at the bottom of this screen shot

Below the list of fields, you will see where you can add another column (shown at the
bottom of Figure 10.2). The details are as follows.
Find the item labeled Add 1, select the radio button labeled After, and use the drop-
down menu to select registration_date. Alternatively, select the radio button labeled At end of
table then click the Go button.

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 28 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

You will be taken to the next screen as shown in Figure 10.3.

Figure 10.3. Creating the title and attributes for the new user_level column

Insert the new column name and its attributes as follows:


• Name: user_level
• Type: TINYINT
• Value: 1
• Default: None
• Attributes: UNSIGNED
When you are satisfied with the attributes, click the Save button. The new column will
be created.

The next step is to launch XAMPP and access the page by entering
http://localhost/login/index.php into the address field of a browser. When the index page
appears, click the Register button on the header menu and register this user as an ordinary
member:

• First name: James


• Last name: Smith
• E-mail: [email protected]
• Password: blacksmith
When using his proper e-mail address and password, James Smith can view the
members’ special pages but he cannot view or amend a list of members.

We will now appoint James Smith to be the membership secretary, with the right to
administer the membership list. For security, he needs a second name and a pseudo e-mail
address and password to access the administration section; therefore, he needs an additional
registration identity. The second e-mail address is important because his office colleagues
probably know his personal e-mail address. Every effort must be made to keep the
administrator’s login details secret. The e-mail address should be fictitious, but it must conform
to the accepted format for e-mails. Now register the membership secretary a second time using
his pseudonym (“Jack”), the new e-mail address, and the new password as follows:

• First name: Jack


• Last name: Smith
• E-mail: [email protected]
• Password: dogsbody

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 29 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

In a real-world situation, you would not use a password that could be easily guessed.
The one I used in this tutorial would not be secure, but I chose it because it is memorable and
therefore helpful for exploring this tutorial.

Now use phpMyAdmin to access the database logindb and the users table. Click the
Browse tab, and find the administrator Jack Smith’s record, as shown in Figure 10.4. If you click
the Edit link, you will be able to change his user_level field from 0 to 1. Click the Go button to
save the change.

Figure 10.4. Find Jack Smith’s record so that you can edit his user_level

 The Header for the Login Page


Figure 10.5 shows the login header with three menu buttons

Figure 10.5. The login page header

The code for the login header appears in Listing 10.2.

Listing 10.2. Creating the Header for the Login Page (login-header.php)
<div id="header">
<h1>This is the header</h1>
<div id="reg-navigation">
<ul>
<li><a href="login.php">Erase Entries</a></li>
<li><a href="register-page.php">Register</a></li>
<li><a href="index.php">Cancel</a></li>
</ul>
</div>

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 30 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

</div>

Now we need to look at a procedure for limiting access to the table of members. We will
prevent general users and registered members from viewing the table, but we will allow the
administrator to view the table and amend records.

The appearance of the login page is shown in Figure 10.6.

Figure 10.6. The login page

The form fields for the e-mail address and password could have been located in the code in the
login page, but for increased security, an external included file is used. A malevolent person
would then have the difficulty of assembling the components before he could interfere with the
form, especially when the components are PHP files and they are located in different folders.
The listing for the login page uses the include() function to pull the form’s fields into the page
from the file named login-page.inc.php. Note that the redundant buttons have been removed
from the heading on this page.

 The Login Page


Now that we have a user_level column, we can create the login page to include two
conditionals. The conditionals will recognize the user_level of the administrator (user_level 1)
and the ordinary member (user_level 0). When the genuine administrator logs in, he will see
the administration page complete with his new menu buttons. When registered members log
in, they will be redirected to the members’ page. The new login page header is pulled into the
page by means of the include statement in bold type in Listing10.3a.
Listing 10.3a. Creating the Login Page (login.php)
<!doctype html>
<html lang=en>
<head>
<title>The Login page</title>
<meta charset=utf-8>
<link rel="stylesheet" type="text/css" href="includes.css">
</head>
<body>
<div id="container">

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 31 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

<?php include("login-header.php"); ?>


<?php include("nav.php"); ?>
<?php include("info-col.php"); ?>
<div id="content"><!-- Start of the login page content. -->
<?php
// This section processes submissions from the login form
// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
//connect to database
require ('mysqli_connect.php'); #1
// Validate the email address
if (!empty($_POST['email'])) {
$e = mysqli_real_escape_string($dbcon, $_POST['email']);
} else {
$e = FALSE;
echo '<p class="error">You forgot to enter your email address.</p>';
}
// Validate the password
if (!empty($_POST['psword'])) {
$p = mysqli_real_escape_string($dbcon, $_POST['psword']);
} else {
$p = FALSE;
echo '<p class="error">You forgot to enter your password.</p>';
}
if ($e && $p){//if no problems #2
// Retrieve the user_id, first_name and user_level for that email/password
combination
$q = "SELECT user_id, fname, user_level FROM users WHERE (email='$e' AND
psword=SHA1('$p'))";
// Run the query and assign it to the variable $result
$result = mysqli_query ($dbcon, $q);
// Count the number of rows that match the email/password combination
if (@mysqli_num_rows($result) == 1) {//if one database row (record) matches
the input:-
// Start the session, fetch the record and insert the three values in an
array
session_start(); #3
$_SESSION = mysqli_fetch_array ($result, MYSQLI_ASSOC);
// Ensure that the user level is an integer.
$_SESSION['user_level'] = (int) $_SESSION['user_level'];
// Use a ternary operation to set the URL #4

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 32 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

$url = ($_SESSION['user_level'] === 1) ? 'admin-page.php' : 'members-


page.php';
header('Location: ' . $url); // Make the browser load either the members’
or the admin page
exit(); // Cancel the rest of the script
mysqli_free_result($result);
mysqli_close($dbcon);
} else { // No match was made.
echo '<p class="error">The e-mail address and password entered do not match
our records
<br>Perhaps you need to register, just click the Register button on the
header menu</p>';
}
} else { // If there was a problem.
echo '<p class="error">Please try again.</p>';
}
mysqli_close($dbcon);
} // End of SUBMIT conditional.
?>
<!-- Display the form fields--> #5
<div id="loginfields">
<?php include ('login_page.inc.php'); ?>
</div><br>
<?php include ('footer.php'); ?>
</div>
</div>
</body>
</html>

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 33 of 34
ASIAN INSTITUTE OF COMPUTER STUDIES
Bachelor of Science in Computer Science
Course Modules
CC225 - Information Management (Database System)
2nd Year – 2nd Semester

References:

1. Lecture Notes on Data Integrity and Constraints


https://www.talend.com/resources/what-is-data-integrity/
https://docs.oracle.com/cd/B19306_01/server.102/b14220/data_int.htm
https://www.c-sharpcorner.com/article/triggers-and-active-databases/
https://www.ibm.com/cloud/learn/database-security
https://www.geeksforgeeks.org/control-methods-of-database-security/
https://www.tutorialspoint.com/Data-Definition-Commands-in-DBMS
http://etutorials.org/SQL/sql+bible/Part+I+SQL+Basic+Concepts+and+Principles/Chapter+1+SQL+and
+Relational+Database+Management+Systems+RDBMS/Brief+History+of+SQL+and+SQL+Standards/

2. Database Systems: Design, Implementation, and Management. Chapter 7 Introduction to Structured


Query Language (SQL). Retrieved from
https://iu.instructure.com/files/59822632/download?download_frd=1

3. West, A. W. (2013). Practical PHP and MySQL Web Site Databases: A Simplified Approach, ISBN-13
(electronic): 978-1-4302-6077-6

Facilitated By:

Name :

MS Teams Account (email) :

Smart Phone Number :

Prepared and Validated By: Ms. Almira Sacriz | Dean Manuel Luis C. Delos Santos, MSCS Page 34 of 34

You might also like