1. Architecture
Request Page
Web Browser
Web Server
Read File
Send
HTML page
Generate
HTML page
Page with
PHP
code
Pass PHP page
and server variables
(GET attributes, Server settings, etc.)
PHP
Interpreter
Interact with
Database
MySQL
2. Introduction to MySQL
Relational databases
Database design
SQL
Creating databases
Creating tables
Selecting from, deleting, and updating tables
Exercises
You should have
Class notes
Exercise handout
MySQL Pocket Reference
Useful resource: http://dev.mysql.com/doc/
3. Basics of Databases
A database is made up of:
fields – a compilation of types of information or properties
records – a compilation of individual items with specific
values for the aforementioned information or properties
For example, a student record could contain fields
such as student id, name, rank, street address, city,
state, and zip code.
A specific record might have a student id of
12345678, name of Jane Smith, rank of sophomore,
street address of 9999 Buttermilk Lane, city of
Johnson City, state of Tennessee, and a zip code of
37601.
4. Relational Databases
A database may contain multiple tables too.
For example, a database used for a section
of a course may need to have a way to
identify a student (student ID), but would not
have to the student's personal information
Therefore, the university's database would
contain multiple tables:
Student information
Course information
Classroom information
5. Basics of Databases (continued)
All of this information is contained in tables
where the rows represent each record and the
columns represent the fields.
6. Relational Databases
A database is a collection of tables
Columns define attributes of the data
All data in a column must have the same data type
A record is stored in a row
table name
row
First Name
Nadia
Madhu
Ajuma
Wade
Helen
Employees
Last Name
Li
Charu
Kinsaka
Randal
Clark
Phone
2687
7856
4489
5257
2147
column
7. "Hey, a table! That's kinda like a
spreadsheet, right?"
Unlike a spreadsheet, the rows (records) of a
database must be independent of one another
Unlike a spreadsheet, the columns (fields) of a
database should be independent of one another
Example: Gradebook with columns for each quiz, test,
and homework grade.
Spreadsheet: one column might be used to compute the final
grade
Database: Cannot have a field for this. Instead, just before
you presented the data (results set), you would calculate a
final grade to be presented. That value is never stored in a
table.
9. Use a Relational Database When…
You have a very large dataset
There is redundant data
Wastes disk space
Increases errors
Security is important
Information must be updated in multiple locations
Different users can be granted different permissions
Strict enforcement of data types is important
10. Spreadsheet Example
Title
A House for Mr. Biswas
Midnight's Children
On the Road
Author
VS Naipaul
Salman Rushdie
Jack Kerouac
Borrower
Sarah
Phone
646.555.1234
11. Spreadsheet Example
Title
A House for Mr. Biswas
Midnight's Children
On the Road
Author
VS Naipaul
Salman Rushdie
Jack Kerouac
Borrower
Sarah
Phone
646.555.1234
One Flew Over the Cuckoo's Nest
Sula
Villette
Ken Kesey
Toni Morrison
Charlotte Bronte
Sarah
646.555.1244
Jim
646.555.4586
Data is inconsistent!
Now imagine you are designing the New York Public
Library database which has tens of million books and
well over a million cardholders.
12. Database Design
Entity Relationship Design
Entity (“thing”, “object”)
Table
Attributes (describe entity)
Columns
Entity Instance
Row
Relationships between entities preserved in relationships
between tables.
If you are interested in learning more formal design
methods look up “normalization” and/or “third normal
form”.
13. Keys
A key is a field by which records may be
sorted.
There are a number of uses for keys:
A primary key can be used to uniquely identify a
record.
A common key is a key shared by two tables in a
relational database.
A foreign key is a common key that can be used
to identify records from another table.
14. Primary Keys
Each record within a table must somehow be uniquely
identifiable.
For example, how can we make sure that we're looking
at the correct student information in the student table?
Answer: No two students share the same student id.
Siblings may have the same parents, roommates may
have the same address, but no one has identical student
IDs.
Therefore, we can use a field containing the student id to
identify a specific record in the student database.
This unique identification is called the Primary Key.
15. Our tables
• A primary key is a unique identifier for a record in a
table.
• A foreign key in one table refers to the primary key of
another.
16. Simple Relational Database Example
Course Table
Department
Course
Section
Semester
Year
Instructor
CSCI
2800
001
Spring
2006
2
CSCI
2800
201
Spring
2006
1
CSCI
2910
001
Spring
2006
4
CSCI
2910
201
Spring
2006
3
Primary
keys
Instructor Table
ID
Name
E-mail
Phone
1
Bailes
bailes@etsu.edu
423.439.6958
2
Bailey
baileyg@etsu.edu
423.439.6959
3
Laws
lawsm@etsu.edu
423.439.6952
4
Tarnoff
tarnoff@etsu.edu
423.439.6404
17. Databases and the Client/Server Model
Database systems typically reside on the server, but
are not as part of the software providing server
functionality.
An interface must exist between server software and
the database.
Three tier architecture – Server/client model adds
middle layer that handles transactions between client
and database server.
Middle layer provides:
ability to access more than one database with a single
transaction
ability connect to many different types of data sources
ability to prioritize requests before they reach the data base
improved security
18. What is SQL?
(Adapted from material found at http://www.atlasindia.com/sql.htm)
Dr. Edgar F. Codd created a model for data
storage that used a simple programming
language to access the stored data
In 1971, IBM used Dr. Codd's work to created
a simple non-procedural language called
Structured English Query Language
(SEQUEL)
In the late 80's, two standardization
organizations (ANSI and ISO) developed a
standardized version called Structured Query
Language or SQL.
19. What is SQL? (continued)
(Adapted from material found at http://www.atlasindia.com/sql.htm)
SQL is the language used to query all databases.
It is a generic way to access the information in a
database.
Understanding SQL is vital to creating a
database application such as a web interface.
Web
Application
SQL
Database
20. Different SQL Implementations
There are multiple vendors of database
products, each with their own implementation
of SQL
Each product should be compliant with ANSI
standard
Added features or commands do exists.
These are called extensions.
21. Using SQL
Assume that a database structure already
exists, i.e., someone has already created
tables for us containing fields and records.
What sort of things might we want to do to
this database?
Start/end a session with a specific database
Read a record
Insert a new record
Delete an existing record
Edit and restore an existing record
22. Basic SQL Syntax
➔ Data Definition Language (DDL)
• CREATE TABLE / DATABASE / VIEW / etc.....
• ALTER ...
• DROP ...
➔ Data Manipulation Language (DML)
•
•
•
•
SELECT ... FROM / INTO … WHERE ...
INSERT INTO ... VALUES ...
UPDATE … SET … WHERE ...
DELETE FROM … WHERE ...
23. Querying Records
A query is an inquiry to the database for information.
This is done with SELECT.
Syntax:
SELECT *| fieldname [, fieldnames]
FROM tablename [, tablenames] WHERE
fieldname=value ORDER BY fieldname [,
fieldnames]
Example:
SELECT FirstName FROM Customers WHERE
LastName='Smith'
27. Updating a Record
Syntax:
UPDATE tablename SET fieldname=value
WHERE fieldname=value
Example:
UPDATE Customers SET
FirstName='Jeff' WHERE
LastName='Smith'
28. What Is Database Normalization?
Cures the ‘SpreadSheet Syndrome’
Store only the minimal amount of
information.
Remove redundancies.
Restructure data.
29. What are the Benefits
of Database Normalization?
Decreased storage requirements!
1 VARCHAR(20)
converted to
1 TINYINT UNSIGNED
in a table of
1 million rows
is a savings of
~20 MB
Faster search performance!
Smaller file for table scans.
More directed searching.
Improved data integrity!
30. What are the Normal Forms?
First Normal Form (1NF)
Second Normal Form (2NF)
Third Normal Form (3NF)
Boyce-Codd Normal Form (BCNF)
Fourth Normal Form (4NF)
Fifth Normal Form (5NF)
32. First Normal Form
Remove horizontal redundancies
Each row must be unique
No two columns hold the same information
No single column holds more than a single
item
Use a primary key
Benefits
Easier to query/sort the data
More scalable
Each row can be identified for updating
33. One Solution
user
first_name last_name phone
first_name
last_name
nickname
phone
cell
pager
address
city
province
postal_code
country
web_url
department
picture
notes
email
Mike
Hillyer
403-555-1717
mike@hoppen.com
Mike
Hillyer
403-555-1919
mhillyer@mysite.com
Tom
Jensen
403-555-1919
tom@openwin.org
Tom
Jensen
403-555-1313
tom@supersite.org
Ray
Smith
403-555-1919
ray@cpma.com
Ray
Smith
403-555-1111
•
•
•
Multiple rows per user
Emails are associated with only one other phone
Hard to Search
35. Forming Relationships
Three Forms
One to One
Same Table?
One to Many
One to (zero or) One
One to (zero or) Many
Many to Many
Place PK of the One in the Many
Many to Many
Create a joining table
37. Our User Table
first_name last_name company
department
Mike
Hillyer
MySQL
Documentation
Tom
Jensen
CPNS
Finance
Ray
Smith
CPNS
Documentation
user
PK
user_id
first_name
last_name
nickname
address
city
province
postal_code
country
web_url
picture
notes
email_format
phone
user_phone
PK,FK1 phone_id
PK
user_id
type
email
PK
address
FK1
user_id
PK
phone_id
country_code
number
extension
38. Second Normal Form
Table must be in First Normal Form
Remove vertical redundancy
Composite keys
The same value should not repeat across rows
All columns in a row must refer to BOTH parts
of the key
Benefits
Increased storage efficiency
Less data repetition
39. Satisfying 2NF
email
email
PK address
PK address
type
FK1 user_id
FK1 user_id
user
user
PK user_id
PK user_id
first_name
last_name
first_name
nickname
last_name
address
nickname
city
address
province
city
postal_code
province
country
postal_code
web_url
country
picture
web_url
notes
picture
email_format
notes
phone
user_phone
PK,FK1 user_id
PK,FK2 phone_id
PK
phone_id
country_code
number
extension
type
user_company
PK,FK1 user_id
PK,FK2 company_id
department
company
PK
company_id
name
40. Third Normal Form
Table must be in Second Normal Form
If your table is 2NF, there is a good chance it is
3NF
All columns must relate directly to the
primary key
Benefits
No extraneous data
43. Joining Tables
Two Basic Joins
Equi-Join
Equi-Join
Outer Join (LEFT JOIN)
SELECT user.first_name, user.last_name, email.address
FROM user, email
WHERE user.user_id = email.user_id
LEFT JOIN
SELECT user.first_name, user.last_name, email.address
FROM user LEFT JOIN email
ON user.user_id = email.user_id
44. De-Normalizing Tables
Use with caution
Normalize first, then de-normalize
Use only when you cannot optimize
Try temp tables, UNIONs, VIEWs,
subselects first