mysql - old dominion universitysainswor/uploads/cs418-s13/cs418s13-04-mysql.… · super hero...

35
CS 418 Web Programming Spring 2013 MYSQL SCOTT G. AINSWORTH http:// www.cs.odu.edu /~ sainswor /CS418-S13/

Upload: lengoc

Post on 22-Aug-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

CS 418 Web Programming

Spring 2013

MYSQL

SCOTT G. AINSWORTH

http://www.cs.odu.edu/~sainswor/CS418-S13/

Page 2: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

OUTLINE Assigned Reading

• Chapter 3 “Using PHP5 with MySQL”

• Chapter 10 “Building

Databases”

• Resource: http://dev.mysql.com/doc/

Quick review of relational databases

• normalization •  referential integrity

Basic MySQL commands

Ch 3 Code Example Demo/Walkthrough

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

2

Page 3: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

RELATIONAL DATABASE Collection of data organized in tables that can be used to create, retrieve, delete, and update that data in many ways

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

3

Page 4: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

DATABASE KEYS Column where each item of data appears only once in that column

Uniquely identifies the row

Primary key – unique identifier for the table

Foreign key – matches the primary key of another table

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

4

Page 5: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

SUPER HERO EXAMPLE

name real name

power 1 power 2 power 3 lair address

city state zip

Clean Freak

John Smith

Strength X-ray vision

flight 123 Poplar Ave

Townsburg OH 45293

Soap Stud Efram Jones

Speed 123 Poplar Ave

Townsburg OH 45293

The Dustmite

Dustin Huff

Strength Dirtiness Laser Vision

452 Elm St. #3D

Burgtown OH 45201

What if we need to add a super hero with more than 3 powers?

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

5

Page 6: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

1ST NORMAL FORM Eliminate repeating columns

Add primary key to table •  Unique •  Must not change

Maintain “atomicity“ •  Each cell is atomic, has only one item of data

name real name

power 1 power 2 power 3 lair address

city state zip

Clean Freak

John Smith

Strength X-ray vision

flight 123 Poplar Ave

Townsburg OH 45293

Soap Stud Efram Jones

Speed 123 Poplar Ave

Townsburg OH 45293

The Dustmite

Dustin Huff

Strength Dirtiness Laser Vision

452 Elm St. #3D

Burgtown OH 45201

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

6

Page 7: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

1NF RESULT Eliminate repeating columns

Add primary key to tables

Each attribute is atomic

id name realname

power lairaddress

city state zip

1 CleanFreak

JohnSmith

Strength 123PoplarAve

Townsburg OH 45293

1 CleanFreak

JohnSmith

X-rayvision

123PoplarAve

Townsburg OH 45293

1 CleanFreak

JohnSmith

flight 123PoplarAve

Townsburg OH 45293

2 SoapStud

EframJones

Speed 123PoplarAve

Townsburg OH 45293

3 TheDustmite

DustinHuff

Strength 452Elm St.#3D

Burgtown OH 45201

3 TheDustmite

DustinHuff

Dirtiness 452Elm St.#3D

Burgtown OH 45201

3 TheDustmite

DustinHuff

LaserVision

452Elm St.#3D

Burgtown OH 45201

What if John Smith changes his name?

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

7

Page 8: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

2ND NORMAL FORM Honor 1st Normal Form

Create separate tables for data duplicated across rows

Be aware of relationships! •  1:1 •  1:m •  m:n

id name realname

power lairaddress

city state zip

1 CleanFreak

JohnSmith

Strength 123PoplarAve

Townsburg OH 45293

1 CleanFreak

JohnSmith

X-rayvision

123PoplarAve

Townsburg OH 45293

1 CleanFreak

JohnSmith

flight 123PoplarAve

Townsburg OH 45293

2 SoapStud

EframJones

Speed 123PoplarAve

Townsburg OH 45293

3 TheDustmite

DustinHuff

Strength 452Elm St.#3D

Burgtown OH 45201

3 TheDustmite

DustinHuff

Dirtiness 452Elm St.#3D

Burgtown OH 45201

3 TheDustmite

DustinHuff

LaserVision

452Elm St.#3D

Burgtown OH 45201

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

8

Page 9: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

2NF RESULT

Satisfy 1NF

Create separate tables for data duplicated across rows

id power1 Strength2 X-Ray

vision3 Flight4 Speed5 Dirtiness6 Laser

Vision

id lair_id name realname

align

1 1 CleanFreak

JohnSmith

good

2 1 SoapStud

EframJones

good

3 2 TheDustmite

DustinHuff

evil

id lairaddress

city state zip

1 123 PoplarAve

Townsburg OH 45293

2 452 ElmSt. #3D

Burgtown OH 45201

char_id power_id1 11 21 32 43 13 53 6

Are “city” and “state” directly related to the lairs?

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

9

Page 10: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

3RD NORMAL FORM

Honor 1st and 2nd Normal Form

Create separate tables for any transitive or partial dependencies

id lairaddress

city state zip

1 123 PoplarAve

Townsburg OH 45293

2 452 ElmSt. #3D

Burgtown OH 45201

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

10

Page 11: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

3NF RESULT

Satisfy 2NF

Create separate tables for any transitive or partial dependencies

id power1 Strength2 X-Ray

vision3 Flight4 Speed5 Dirtiness6 Laser

Vision

id lair_id name realname

align

1 1 CleanFreak

JohnSmith

good

2 1 SoapStud

EframJones

good

3 2 TheDustmite

DustinHuff

evil

id zip_id lairaddress

1 45293 123 PoplarAve

2 45201 452 ElmSt. #3D

id city state45293 Townsburg OH45201 Burgtown OH

char_id power_id1 11 21 32 43 13 53 6

see note on p. 283 on why good/evil is not in a separate table

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

11

Page 12: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

THAT’S ABOUT AS FAR AS WE’LL GO Other normal forms are possible (BCNF, 4NF, 5NF)

•  take a database class if you’re interested

Referential integrity

•  a foreign key (“link”) into another table is no longer valid •  “404 Errors” are bad in databases and should not happen

•  how bad is a function of the data itself…

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

12

Page 13: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

STANDARDIZATION Table names

• descriptive – describe their main function and the application they belong to

•  relatively short •  lowercase

Column names •  lowercase •  short •  separate words by ‘_’

Primary keys • single primary keys

always called ‘id’

Foreign keys • end with ‘id’ • start with table

descriptor

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

13

Page 14: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

MYSQL HIERARCHY FOR CS 418/518

server = sainsworth418.cs.odu.edu

database=sainsworth

movie_main movie_people

movie_type

char_main char_power

char_lair

We’re sharing a single server, so each student has a single database (same as your username). Table names should start with the project or application name.

database=student1 database=student2

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

14

Page 15: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

MANIPULATING TABLES AND DATABASES CREATE - create new databases, tables

ALTER - modify existing tables

DELETE - erase data from tables

DESCRIBE - show structure of tables

INSERT INTO tablename VALUES - put data in table

UPDATE - modify data in tables

DROP - destroys table or database (values + structure) more: http://dev.mysql.com/doc/refman/5.0/en/sql-syntax.html

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

15

Page 16: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

NATIVE MYSQL DATA TYPES Unlike Perl, PHP and other civilized languages, MySQL is big into data types:

•  http://dev.mysql.com/doc/refman/5.0/en/data-types.html •  pgs. 86-90 in Ch 3 •  many examples in Chs 3, 10

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

16

Page 17: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

SQL QUERY FORM

SELECT [fieldnames] FROM [tablenames] WHERE [criteria] ORDER BY [fieldname to sort on] [DESC] LIMIT [offset, maxrows]

more: http://dev.mysql.com/doc/refman/5.0/en/select.html look at chapters 3 and 10 for code examples

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

17

Page 18: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

SQL JOINS Pull in data from two different tables

INNER JOIN •  find intersection between two

tables

FULL OUTER JOIN •  produce set of all records in

both tables

LEFT JOIN (or, LEFT OUTER JOIN)

•  for each item in Table A, find some data in Table B

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

18

Page 19: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

PHP AND MYSQL mysql_connect (“hostname”, “user”, “pass”)

•  connect to the MySQL server

mysql_select_db (“database name”) •  makes the named database the active one

mysql_query (“query”) •  send any type of MySQL command to server

mysql_fetch_array(“results from query”) •  returns several rows of the query

mysql_error() •  shows the error message generated by the MySQL server

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

19

Page 20: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

PHP AND MYSQL CONFIG.PHP

<?php define (‘SQL_HOST’, ‘localhost’); define (‘SQL_USER’, ‘username’); define (‘SQL_PASS’, ‘passwd’);

define (‘SQL_DB’, ‘username’); ?>

This way you don’t have to include your plaintext username and password in your source files:

require (‘config.php’); mysql_connect (SQL_HOST, SQL_USER, SQL_PASS); mysql_select_db(SQL_DB);

Put config.php in ~/cs418_html/

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

20

Page 21: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

PHPMYADMIN Access your MySQL databases through a GUI

Change your password

Create, edit, delete tables

Run (and test) queries

View and print table structure https://sainsworth418.cs.odu.edu/

phpmyadmin

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

21

Page 22: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

OUTLINE Quick review of relational databases

• normalization •  referential integrity

Basic MySQL commands

Ch 3 Code Example Demo/Walkthrough

Next Time: MySQL Lab Next Week: Tables, Forms Assigned Reading: Chs 4, 5

Reminder: Groups due Feb 7

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

22

Page 23: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

DEMO/WALKTHROUGH TIME Examples from Chapter 3

•  Creating a Database •  Querying the Database •  PHP and Arrays of Data •  Multiple Tables

https://sainsworth418.cs.odu.edu/~sainswor/textbook/ch03.htm

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

23

Page 24: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

MOVIE TABLES

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

24

Page 25: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

MOVIE DATA movie_main

movie_people movie_type

1/31/13 CS 418 Web Programming • Spring 2013 • Ainsworth

25

Page 26: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

JUST A COUPLE THINGS Joins

Deprecated PHP/MySQL syntax

fetch_array() vs. fetch_assoc() vs. fetch_row()

CS 418/518 - Fall 2012 26

Page 27: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

SQL JOINS JOIN: Return rows when there is at least one match in both tables

•  same as INNER JOIN •  http://www.w3schools.com/sql/sql_join_inner.asp

LEFT JOIN: Return all rows from the left table, even if there are no matches in the right table

•  http://www.w3schools.com/sql/sql_join_left.asp

RIGHT JOIN: Return all rows from the right table, even if there are no matches in the left table

•  http://www.w3schools.com/sql/sql_join_right.asp

FULL JOIN: Return rows when there is a match in one of the tables

•  http://www.w3schools.com/sql/sql_join_full.asp

CS 418/518 - Fall 2012 27

http://www.w3schools.com/sql/sql_join.asp

Page 28: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

SQL JOINS Pull in data from two different tables

INNER JOIN •  find intersection between two tables

FULL OUTER JOIN

• produce set of all records in both tables LEFT JOIN (or, LEFT OUTER JOIN)

•  for each item in Table A, find some data in Table B

CS 418/518 - Fall 2012 28

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Page 29: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

DEPRECATED FUNCTIONS The entire mysql_* API for PHP has been deprecated and should no longer be used

•  just happened in July 2011

We're going to use the mysqli (MySQL Improved) API

Comparison of accepted APIs •  http://www.php.net/manual/en/mysqlinfo.api.choosing.php

CS 418/518 - Fall 2012 29

Page 30: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

PHP AND MYSQL } Connect to server

}  DEPRECATED: mysql_connect ("hostname", "user", "pass") }  MySQLI: $mysqli = new mysqli ("hostname", "user", "pass", "db")

} Send query to server }  DEPRECATED: mysql_query ("query") }  MySQLI: $results = $mysqli->query("query")

} Shows error message }  DEPRECATED: mysql_error() }  MySQLI: $mysqli->error

} Release results array }  $results->free()

} Close connection }  $mysqli->close();

CS 418/518 - Fall 2012 30

Page 31: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

FETCHING RESULTS MYSQLI General Note

•  If two or more columns of the result have the same field (column) names, the last column will take precedence and overwrite the earlier data

•  Can use alias in SELECT statement (AS keyword) •  Can use numeric array index

$results->fetch_array() •  stores data in both the numeric indices of the result array

AND in associative indices using the field (column) name as the key

CS 418/518 - Fall 2012 31

Page 32: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

FETCH_ARRAY

CS 418/518 - Fall 2012 32

lab1_store id name qty price 1 apple 10 1 2 pear 5 2 3 banana 10 1.5 4 lemon 100 0.1 5 orange 50 0.2

$query="SELECT * " . "FROM lab1_store "; $results = $mysqli->query($query) or die ($mysqli->error.__LINE__); $row = $results->fetch_array(); print_r($row);

Array( [0] => 1 [id] => 1 [1] => apple [name] => apple [2] => 10 [qty] => 10 …)

Page 33: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

$query="SELECT * " . "FROM lab1_store "; $results = $mysqli->query($query) or die ($mysqli->error.__LINE__); $row = $results->fetch_assoc();// Following line produces the same results// $row = $results->fetch_array(MYSQLI_ASSOC); print_r($row);

FETCH_ASSOC

CS 418/518 - Fall 2012 33

lab1_store id name qty price 1 apple 10 1 2 pear 5 2 3 banana 10 1.5 4 lemon 100 0.1 5 orange 50 0.2

Array( [id] => 1 [name] => apple [qty] => 10 [price] => 1)

Page 34: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

$query="SELECT * " . "FROM lab1_store "; $results = $mysqli->query($query) or die ($mysqli->error.__LINE__); $row = $results->fetch_row();// Following line produces the same results// $row = $results->fetch_array(MYSQLI_NUM); print_r($row);

FETCH_ROW

CS 418/518 - Fall 2012 34

lab1_store id name qty price 1 apple 10 1 2 pear 5 2 3 banana 10 1.5 4 lemon 100 0.1 5 orange 50 0.2

Array( [0] => 1 [1] => apple [2] => 10 [3] => 1)

Page 35: MYSQL - Old Dominion Universitysainswor/uploads/CS418-S13/cs418s13-04-MySQL.… · SUPER HERO EXAMPLE name real name power 1 power 2 power 3 lair address city state zip Clean Freak

LAB ASSIGNMENT

Table Normalization •  did this on Tuesday

Store Inventory

•  single table, simple SELECT construction Courses

•  3 tables, using JOINS

CS 418/518 - Fall 2012 35

http://www.cs.odu.edu/~sainswor/CS418-S13/Lab1-MySQL