44
Architecture Web Browser Web Server Request Page Page with PHP code Read File PHP Interpreter Pass PHP page and server variables (GET attributes, Server settings, etc.) Generate HTML page Send HTML page MySQL Interact with Database

My sql

Embed Size (px)

Citation preview

Page 1: My sql

Architecture

Web Browser Web ServerRequest Page

Page with PHPcode

Read File

PHP Interpreter

Pass PHP pageand server variables(GET attributes, Server settings, etc.)

Generate HTML page

Send HTML page

MySQLInteract withDatabase

Page 2: My sql

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/

Page 3: My sql

Basics of DatabasesA 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.

Page 4: My sql

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

Page 5: My sql

Basics of Databases (continued) All of this information is contained in tables

where the rows represent each record and the columns represent the fields.

Page 6: My sql

First Name Last Name PhoneNadia Li 2687Madhu Charu 7856Ajuma Kinsaka 4489Wade Randal 5257Helen Clark 2147

Employees

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

column

row

Page 7: My sql

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

Page 8: My sql

Relational Databases (continued)Student Table•ID•Name•Z-account•Rank•Address•Phone number

Instructor Table•ID•Name•E-mail address•Department•Office location•Office phone

Course Table•Course ID•Catalog description•Credit hours•List of topics

Course Section Table•Course•Section number •Instructor•Students

Page 9: My sql

Use a Relational Database When…

You have a very large dataset There is redundant data

Wastes disk space Increases errors

Information must be updated in multiple locations

Security is important Different users can be granted different permissions

Strict enforcement of data types is important

Page 10: My sql

Spreadsheet Example

Title Author Borrower PhoneA House for Mr. Biswas VS Naipaul Sarah 646.555.1234Midnight's Children Salman RushdieOn the Road Jack Kerouac

Page 11: My sql

Spreadsheet Example

Title Author Borrower PhoneA House for Mr. Biswas VS Naipaul Sarah 646.555.1234Midnight's Children Salman RushdieOn the Road Jack Kerouac

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.

One Flew Over the Cuckoo's Nest Ken Kesey Sarah 646.555.1244Sula Toni MorrisonVillette Charlotte Bronte Jim 646.555.4586

Page 12: My sql

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

Page 13: My sql

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.

Page 14: My sql

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.

Page 15: My sql

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.

Page 16: My sql

Simple Relational Database Example

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

ID Name E-mail Phone

1 Bailes [email protected] 423.439.6958

2 Bailey [email protected] 423.439.6959

3 Laws [email protected] 423.439.6952

4 Tarnoff [email protected] 423.439.6404

Instructor Table

Course Table

Primarykeys

Page 17: My sql

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

Page 18: My sql

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.

Page 19: My sql

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.

WebApplication

DatabaseSQL

Page 20: My sql

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.

Page 21: My sql

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

Page 22: My sql

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

Page 23: My sql

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'

Page 24: My sql

Data Manipulation

There are three basic commands to manipulate data: INSERT DELETE UPDATE

Page 25: My sql

Adding a Record

Syntax:

INSERT INTO tablename (fieldname [, fieldnames]) VALUES (value [, values])

Example:

INSERT INTO Customers (FirstName, LastName) VALUES ('Jane','Smith')

Page 26: My sql

Removing a Record Syntax:

DELETE FROM tablename WHERE fieldname=value

Example:

DELETE FROM Customers WHERE LastName='Jones'

Page 27: My sql

Updating a Record Syntax:

UPDATE tablename SET fieldname=value WHERE fieldname=value

Example:

UPDATE Customers SET FirstName='Jeff' WHERE LastName='Smith'

Page 28: My sql

What Is Database Normalization?

Cures the ‘SpreadSheet Syndrome’ Store only the minimal amount of

information. Remove redundancies. Restructure data.

Page 29: My sql

What are the Benefitsof 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!

Page 30: My sql

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)

Page 31: My sql

Our Table

name phone1 phone2 email1 email2Mike Hillyer

403-555-1717

403-555-1919

[email protected]

[email protected]

Tom Jensen

403-555-1919

403-555-1313

[email protected]

[email protected]

Ray Smith 403-555-1919

403-555-1111

[email protected]

user

namenicknamephone1phone2phone3cellpageraddresscityprovincepostal_codecountryemail1email2web_urlcompanydepartmentpicturenotesemail_format

Page 32: My sql

First Normal Form

Remove horizontal redundancies No two columns hold the same information No single column holds more than a single

item

Each row must be unique Use a primary key

Benefits Easier to query/sort the data More scalable Each row can be identified for updating

Page 33: My sql

One Solution

first_name last_name phone emailMike Hillyer 403-555-1717 [email protected]

Mike Hillyer 403-555-1919 [email protected]

Tom Jensen 403-555-1919 [email protected]

Tom Jensen 403-555-1313 [email protected]

Ray Smith 403-555-1919 [email protected]

Ray Smith 403-555-1111

• Multiple rows per user

• Emails are associated with only one other phone

• Hard to Search

user

first_namelast_namenicknamephonecellpageraddresscityprovincepostal_codecountryweb_urldepartmentpicturenotes

Page 34: My sql

Satisfying 1NF

user

PK user_id

first_namelast_namenicknameaddresscityprovincepostal_codecountryweb_urlcompanydepartmentpicturenotes

phone

PK phone_id

country_codenumberextension

email

PK email_id

address

Page 35: My sql

Forming Relationships

Three Forms One to (zero or) One One to (zero or) Many Many to Many

One to One Same Table?

One to Many Place PK of the One in the Many

Many to Many Create a joining table

Page 36: My sql

Joining Tables

user

PK user_id

first_namelast_namenicknameaddresscityprovincepostal_codecountryweb_urlpicturenotesemail_format

email

PK address

FK1 user_id

user_phone

PK,FK1 phone_idPK user_id

type

phone

PK phone_id

country_codenumberextension

Page 37: My sql

user

PK user_id

first_namelast_namenicknameaddresscityprovincepostal_codecountryweb_urlpicturenotesemail_format

email

PK address

FK1 user_id

user_phone

PK,FK1 phone_idPK user_id

type

phone

PK phone_id

country_codenumberextension

Our User Tablefirst_name last_name company departmentMike Hillyer MySQL Documentation

Tom Jensen CPNS Finance

Ray Smith CPNS Documentation

Page 38: My sql

Second Normal Form

Table must be in First Normal Form Remove vertical redundancy

The same value should not repeat across rows

Composite keys All columns in a row must refer to BOTH parts

of the key

Benefits Increased storage efficiency Less data repetition

Page 39: My sql

Satisfying 2NF

email

PK address

typeFK1 user_id

phone

PK phone_id

country_codenumberextensiontype

user

PK user_id

first_namelast_namenicknameaddresscityprovincepostal_codecountryweb_urlpicturenotes

user_phone

PK,FK1 user_idPK,FK2 phone_id

company

PK company_id

name

user_company

PK,FK1 user_idPK,FK2 company_id

department

email

PK address

FK1 user_id

user

PK user_id

first_namelast_namenicknameaddresscityprovincepostal_codecountryweb_urlpicturenotesemail_format

Page 40: My sql

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

Page 41: My sql

Satisfying 3NF

email

PK address

FK1 user_idformat

phone

PK phone_id

country_codenumbertype

user

PK user_id

first_namelast_namenicknameaddresscityprovincepostal_codecountryweb_urlpicturenotes

user_phone

PK,FK1 user_idPK,FK2 phone_id

extension

company

PK company_id

name

user_company

PK,FK1 user_idPK,FK2 company_id

department

Page 42: My sql

Finding Balance

email

PK address

FK1 user_idformat

phone

PK phone_id

FK1 type_idarea_codeNXXNCX

FK2 country_id

user

PK user_id

first_namelast_namenicknameunitstreet_numberstreet_namestreet_typequadrantweb_urlpicturenotes

FK1 postal_code

user_phone

PK,FK1 user_idPK,FK2 phone_id

extension

company

PK company_id

name

user_department

PK,FK1 user_idPK,FK2 department_id

type

PK type_id

type

country

PK country_id

Namephone_code

department

PK department_id

nameFK1 company_id

postal_code

PK postal_code

FK1 city_id

province

PK province_id

NameAbbreviation

FK1 country_id

city

PK city_id

nameFK1 province_id

Page 43: My sql

Joining Tables

Two Basic Joins Equi-Join Outer Join (LEFT JOIN)

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

Page 44: My sql

De-Normalizing Tables

Use with caution Normalize first, then de-normalize Use only when you cannot optimize Try temp tables, UNIONs, VIEWs,

subselects first