93
Lecture 11 Introduction to Relational Database Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

Lecture 11 Introduction to Relational Database

  • Upload
    benard

  • View
    59

  • Download
    1

Embed Size (px)

DESCRIPTION

Lecture 11 Introduction to Relational Database. Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU. CSC382: Internet & Web Technology MySQL Database System. Lecture Contents Database Concepts SQL Commands Database Connectivity Connectivity Example DDL Query DML Query - PowerPoint PPT Presentation

Citation preview

Page 1: Lecture 11 Introduction to  Relational Database

Lecture 11Introduction to Relational Database

Presented ByDr. Shazzad Hosain

Asst. Prof. EECS, NSU

Page 2: Lecture 11 Introduction to  Relational Database

CSC382: Internet & Web TechnologyMySQL Database System

Lecture Contents Database Concepts SQL Commands Database Connectivity

Connectivity Example DDL Query DML Query MySql Functions

Page 3: Lecture 11 Introduction to  Relational Database

3

Client-Server Interaction

MySQLServer

ClientProgram

Make a request(SQL query)

Get results

Client program can be a MySQL command line client, GUI client, or a program written in any language such as C, Perl, PHP, Java that has an interface to the MySQL server.

MySQL databases are ideal for storing that data we have collected about a user or for holding user preferences between visits. It is free and it is easy.

Page 4: Lecture 11 Introduction to  Relational Database

4

3-Tier Architecture

WebBrowser(Client)

DatabaseServer

WebServer PHP

Page 5: Lecture 11 Introduction to  Relational Database

5

Database Management System• Collection of data =

Database (DB)• Set of interrelated

data and programs to access those data is called DBMS

• DBMS Provides environment that is convenient and efficient to use for data retrieval and storage

Data Data Data

Program Program

ProgramProgram

Database

DBMS

Page 6: Lecture 11 Introduction to  Relational Database

Relational Database Basics• Today’s database implementations are almost all based on the

relational model• A relational database management system consists of a number of

databases.• Each database consists of a number of tables.• It represents data in a two-dimensional table called a relation• The attributes are located across the top of the relation

attributesname

6

Page 7: Lecture 11 Introduction to  Relational Database

Tuples• The rows in the relation (other than attribute row) are called tuples• A tuple has one component or value for each attribute of the relation• A tuple should never appear more than once in a relation• We must ensure that the relation has a sufficient set of attributes so

that no two tuples will have the same values for all attributes

tuples

7

Page 8: Lecture 11 Introduction to  Relational Database

8

Database Languages (Query) DBMS provide two types of language

– One to specify schema and create the database– One to express database queries and updates

1. Data-Definition Language (DDL Query)– Schema is specified by a set of definitions expressed by the DDL– Result is set of tables stored in the Data Dictionary– Data Dictionary is a file that contains metadata, data about data

2. Data-Manipulation Language (DML Query)– Language for accessing and manipulating the data organized by

the appropriate data model. That is, data retrieval, insertion, deletion, modification

Page 9: Lecture 11 Introduction to  Relational Database

9

SQL commands SHOW, USE

• SHOW– Display databases or tables in current database;– Example (command line client):– show databases;– show tables;

• USE– Specify which database to use– Example– use bookstore;

Page 10: Lecture 11 Introduction to  Relational Database

10

Entering commands (1)

• Show all the databases– SHOW DATABASES;mysql> SHOW DATABASES;+-------------+| Database |+-------------+| bookstore || employee_db || mysql || student_db || test || web_db |+-------------+

Page 11: Lecture 11 Introduction to  Relational Database

11

Entering commands (2)

• Choosing a database and showing its tables– USE test;SHOW tables;mysql> USE test;Database changedmysql> SHOW tables;+----------------+| Tables_in_test |+----------------+| books || name2 || names || test |+----------------+4 rows in set (0.00 sec)mysql>

Page 12: Lecture 11 Introduction to  Relational Database

12

Entering commands (3)

• Show the structure of a table– DESCRIBE names;

mysql> DESCRIBE names;+-----------+-------------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+-----------+-------------+------+-----+---------+----------------+| id | int(11) | | PRI | NULL | auto_increment || firstName | varchar(20) | | | | || lastName | varchar(20) | | | | |+-----------+-------------+------+-----+---------+----------------+3 rows in set (0.00 sec)

mysql>

Page 13: Lecture 11 Introduction to  Relational Database

13

SQL Commands• SQL is a reasonably powerful query language.

• However it is incredibly simple. You can learn it in a night.

• The fundamental SQL commands are:

– CREATE– SELECT– INSERT– DELETE– UPDATE

Page 14: Lecture 11 Introduction to  Relational Database

14

Example of SQL DDL

studentID first_name

USE test;CREATE TABLE marks ( studentID SMALLINT AUTO_INCREMENT NOT NULL, first_name VARCHAR(20) NOT NULL, last_name VARCHAR(20) NOT NULL, mark SMALLINT DEFAULT 0 NOT NULL, PRIMARY KEY (studentID));

markstable

last_name mark

Page 15: Lecture 11 Introduction to  Relational Database

15

marks.sql

-- Insert some rows into marks tableINSERT INTO marks (first_name, last_name, mark) VALUES ('Fred', 'Jones', 78);INSERT INTO marks (first_name, last_name, mark) VALUES ('Bill', 'James', 67);INSERT INTO marks (first_name, last_name, mark) VALUES ('Carol', 'Smith', 82);INSERT INTO marks (first_name, last_name, mark) VALUES ('Bob', 'Duncan', 60);INSERT INTO marks (first_name, last_name, mark) VALUES ('Joan', 'Davis', 86);

Page 16: Lecture 11 Introduction to  Relational Database

16

Conditional Creation

• Conditional database creation– CREATE DATABASE IF NOT EXISTS db_name;

• Conditional table creation– CREATE TABLE IF NOT EXISTS table_name;

Page 17: Lecture 11 Introduction to  Relational Database

17

• Selecting the complete tableSELECT * FROM marks;

+-----------+------------+-----------+------+| studentID | first_name | last_name | mark |+-----------+------------+-----------+------+| 1 | Fred | Jones | 78 || 2 | Bill | James | 67 || 3 | Carol | Smith | 82 || 4 | Bob | Duncan | 60 || 5 | Joan | Davis | 86 |+-----------+------------+-----------+------+5 rows in set (0.00 sec)

Entering commands

Page 18: Lecture 11 Introduction to  Relational Database

PHP to MySQL Connectivity• mysql_connect() establishes a connection to a MySQL

server. • It takes 3 parameters.

– The address of the server– Your Username for that db account– Your password

$conn = mysql_connect(“address",“user“,“pass”);

• XAMPP mysql server is found at the following address: localhost

18

Page 19: Lecture 11 Introduction to  Relational Database

• In our code mysql_select_db() then tells PHP that any queries we make are against the mydb database.

mysql_select_db(“dbname",$conn);• We could create multiple connections to

databases on different servers. But for now, you’ll only need one database.

• mysql_query() does all the hard work.• Using the database connection identifier, it sends a line

of SQL to the MySQL server to be processed. • This is the key command for interacting with the

database.

PHP to MySQL Connectivity

19

Page 20: Lecture 11 Introduction to  Relational Database

Extracting Query Result

• Finally, mysql_result() is used to display the values of fields from our query:

mysql_result($result,0,"first");

• Using $result, we go to the first row, which is numbered 0, and return the value of the specified fields.

• Close the connection to the database server mysql_close();

20

Page 21: Lecture 11 Introduction to  Relational Database

First MySql/PHP Program<?$db = mysql_connect("localhost", "root"); mysql_select_db("mydb",$db);$result = mysql_query("SELECT * FROM

employees");

$firstname = mysql_result($result,0,"first");$lastname = mysql_result($result,0,“last");$address = mysql_result($result,0,“address");

?>

Hello <?=$firstname?> <?=$lastname?> <BR>Your address is <?=$address?>

21

Page 22: Lecture 11 Introduction to  Relational Database

Unpolitically Correct Create Example

• For example, to create a table from our PHP code you might type:

mysql_query(“CREATE TABLE players ( name varchar(30),

age integer)”);

• Remember that this is something that you would only want to do once – once the table is created we don’t want to wipe it by accident

22

Page 23: Lecture 11 Introduction to  Relational Database

MySQL Insert Example• Equally we can populate our tables with INSERT statements via

mysql_query()

mysql_query(“INSERT INTO player VALUES (‘Zidane',32)”);

mysql_query(“INSERT INTO player VALUES (‘Ronaldinho',28)”);

mysql_query(“INSERT INTO player VALUES (‘Pele',58)”);

• These are hard coded examples – but we could be using variables in these statements

23

Page 24: Lecture 11 Introduction to  Relational Database

Mysql Select Example

• We use a SELECT statement to grab data from a certain table and then put the result into a variable ready to analyse…

$result = mysql_query(“SELECT * FROM players WHERE age<35”);

• However now result has all the info we want inside it… how are we going to extract it in the form we want?

24

Page 25: Lecture 11 Introduction to  Relational Database

mysql_fetch_row()• mysql_This function gets a result row as an enumerated array.• subsequent calls to mysql_fetch_row() would return the next row

in the result set, or FALSE if there are no more rows.<? mysql_connect(“mysql_address", "mysql_user", "mysql_pass"); mysql_select_db(“dbname");

$result = mysql_query("SELECT name, age FROM players");

while ($player = mysql_fetch_array($result)) {

print “Player $player[name] is “;print “$player[age] years old”;

}

mysql_free_result($result);?>

25

Page 26: Lecture 11 Introduction to  Relational Database

mysql_num_rows()

• mysql_num_rows() returns the number of rows in a result set. This command is only valid for SELECT statements.

mysql_query(“SELECT * FROM players WHERE age<35);print mysql_num_rows().“players are younger than 35";

• It’s a great function for when you need to loop round all the results in your query, or just to know how many matches you got

26

Page 27: Lecture 11 Introduction to  Relational Database

mysql_rows_affected()• mysql_affected_rows() returns the number

of rows affected by the last INSERT, UPDATE or DELETE query associated with. For example:

mysql_query("DELETE FROM mytable WHERE id < 10");

print "Records deleted: ".mysql_affected_rows()."<BR>";

• N.b. this function does not work with SELECT statements - only on statements which modify records.

27

Page 28: Lecture 11 Introduction to  Relational Database

28

A db_connect Function

• This function can be used in scripts to connect to a database. Put it in a file called db_connect.php in your include path

<?php function db_connect($db_name){ $host_name = "localhost:3306"; $user_name = "xxxxx"; $password = "yyyyy"; $db_link = mysql_connect($host_name, $user_name, $password) or die("Could not connect to $host_name"); mysql_select_db($db_name) or die("Could not select database $db_name"); return $db_link;} ?>

Page 29: Lecture 11 Introduction to  Relational Database

29

The SELECT Command

• There are many other variations of the select command.

• Example: finding the number of records in a table assuming a primary key called id:

• Can also perform searching using the WHERE option

SELECT COUNT(id) FROM table_name

Page 30: Lecture 11 Introduction to  Relational Database

30

MySQL Functions (1)

• How many rows are there ?

• Can use COUNT(marks) instead of COUNT(*)

SELECT COUNT(*) FROM marks;

+----------+| COUNT(*) |+----------+| 5 |+----------+1 row in set (0.00 sec)

Page 31: Lecture 11 Introduction to  Relational Database

31

MySQL Functions (2)

• What is the sum of all the marks?SELECT SUM(mark) FROM marks;

+-----------+| SUM(mark) |+-----------+| 373 |+-----------+1 row in set (0.00 sec)

Page 32: Lecture 11 Introduction to  Relational Database

32

MySQL Functions (3)

• What is the average mark?SELECT AVG(mark) FROM marks;

+-----------+| AVG(mark) |+-----------+| 74.6000 |+-----------+1 row in set (0.00 sec)

Page 33: Lecture 11 Introduction to  Relational Database

33

MySQL Functions (4)

• What is the minimum mark?SELECT MIN(mark) FROM marks;

+-----------+| MIN(mark) |+-----------+| 60 |+-----------+1 row in set (0.00 sec)

Page 34: Lecture 11 Introduction to  Relational Database

34

MySQL Functions (5)

• What is the maximum mark?SELECT MAX(mark) FROM marks;

+-----------+| MAX(mark) |+-----------+| 86 |+-----------+1 row in set (0.00 sec)

Page 35: Lecture 11 Introduction to  Relational Database

35

Entering commands• Updating a record

– UPDATE names SET lastName = 'Stone'WHERE id=3;

– SELECT * FROM names;

mysql> UPDATE names SET lastName = 'Stone' WHERE id=3;Query OK, 1 row affected (0.28 sec)Rows matched: 1 Changed: 1 Warnings: 0mysql> SELECT * FROM names;+----+-----------+------------+| id | firstName | lastName |+----+-----------+------------+| 1 | Fred | Flintstone || 2 | Barney | Rubble || 3 | Ralph | Stone |+----+-----------+------------+3 rows in set (0.00 sec)mysql>

Page 36: Lecture 11 Introduction to  Relational Database

36

The DROP Command

• To delete databases and tables use the DROP command

• Examples– DROP DATABASE db_name;– DROP DATABASE IF EXISTS db_name;– DROP TABLE table_name;– DROP TABLE IF EXISTS table_name;

Note: Don't confuse DROP with DELETE which deletes rowsof a table.

Page 37: Lecture 11 Introduction to  Relational Database

37

The WHERE Clause• Select rows according to some criterion

SELECT * FROM marks WHERE studentID > 1 AND studentID < 5;

+-----------+------------+-----------+------+| studentID | first_name | last_name | mark |+-----------+------------+-----------+------+| 2 | Bill | James | 67 || 3 | Carol | Smith | 82 || 4 | Bob | Duncan | 60 |+-----------+------------+-----------+------+3 rows in set (0.01 sec)

Page 38: Lecture 11 Introduction to  Relational Database

38

The WHERE Clause• Select rows with marks >= 80

SELECT * FROM marks WHERE mark >= 80;

+-----------+------------+-----------+------+| studentID | first_name | last_name | mark |+-----------+------------+-----------+------+| 3 | Carol | Smith | 82 || 5 | Joan | Davis | 86 |+-----------+------------+-----------+------+2 rows in set (0.00 sec)

Page 39: Lecture 11 Introduction to  Relational Database

39

The ORDER BY Clause• Select rows according to some criterion

SELECT * FROM marks ORDER BY mark DESC;

+-----------+------------+-----------+------+| studentID | first_name | last_name | mark |+-----------+------------+-----------+------+| 5 | Joan | Davis | 86 || 3 | Carol | Smith | 82 || 1 | Fred | Jones | 78 || 2 | Bill | James | 67 || 4 | Bob | Duncan | 60 |+-----------+------------+-----------+------+5 rows in set (0.00 sec)

Page 40: Lecture 11 Introduction to  Relational Database

40

Searching Using LIKE (1)

• LIKE is used to search a table for values containing a search string:

• There are two wild-card characters used to specify patterns:– _ matches a single character– % matches zero or more characters

• Can also use NOT LIKE• Searching is case insensitive

Page 41: Lecture 11 Introduction to  Relational Database

41

Searching Using LIKE (2)

• Example: last names in marks table that begin with J

• Example: first names that have 3 letters

SELECT * FROM marks WHERE last_name LIKE 'J%';

SELECT * FROM marks WHERE first_name LIKE '_ _ _';

Page 42: Lecture 11 Introduction to  Relational Database

42

employee_db.sql (1)CREATE TABLE employees ( employeeID SMALLINT NOT NULL, name VARCHAR(20) NOT NULL, position VARCHAR(20) NOT NULL, address VARCHAR(40) NOT NULL, PRIMARY KEY (employeeID));INSERT INTO employees VALUES (1001, 'Fred', 'programmer', '13 Windle St');INSERT INTO employees VALUES (1002, 'Joan', 'programmer', '23 Rock St');INSERT INTO employees VALUES (1003, 'Bill', 'manager', '37 Front St');

Page 43: Lecture 11 Introduction to  Relational Database

43

employee_db.sql (2)CREATE TABLE jobs ( employeeID SMALLINT NOT NULL, hours DECIMAL(5,2) NOT NULL,);INSERT INTO jobs VALUES (1001, 13.5);INSERT INTO jobs VALUES (1002, 2);INSERT INTO jobs VALUES (1002, 6.25);INSERT INTO jobs VALUES (1003, 4);INSERT INTO jobs VALUES (1001, 1);INSERT INTO jobs VALUES (1003, 7);INSERT INTO jobs VALUES (1003, 9.5);

Page 44: Lecture 11 Introduction to  Relational Database

Employee_id name position address

1001 Fred Programmer 13 Windle St

1002 Joan Programmer Rock St

1003 Bill manager 37 Front ST

Database Tables

Employee_id hours

1001 13.5

1002 2

1002 6.25

1003 4

1001 1

1003 7

1003 9.5

Employees tableJobs table

Page 45: Lecture 11 Introduction to  Relational Database

45

Select Queries With Joins (1)• Cartesian product query

SELECT * FROM employees, jobs;

+------------+------+------------+--------------+------------+-------+| employeeID | name | position | address | employeeID | hours |+------------+------+------------+--------------+------------+-------+| 1001 | Fred | programmer | 13 Windle St | 1001 | 13.50 || 1002 | Joan | programmer | 23 Rock St | 1001 | 13.50 || 1003 | Bill | manager | 37 Front St | 1001 | 13.50 || 1001 | Fred | programmer | 13 Windle St | 1002 | 2.00 || 1002 | Joan | programmer | 23 Rock St | 1002 | 2.00 || 1003 | Bill | manager | 37 Front St | 1002 | 2.00 || 1001 | Fred | programmer | 13 Windle St | 1002 | 6.25 || 1002 | Joan | programmer | 23 Rock St | 1002 | 6.25 || 1003 | Bill | manager | 37 Front St | 1002 | 6.25 |

Page 46: Lecture 11 Introduction to  Relational Database

46

Select Queries With Joins (2)• Cartesian product query (continued)| 1001 | Fred | programmer | 13 Windle St | 1003 | 4.00 || 1002 | Joan | programmer | 23 Rock St | 1003 | 4.00 || 1003 | Bill | manager | 37 Front St | 1003 | 4.00 || 1001 | Fred | programmer | 13 Windle St | 1001 | 1.00 || 1002 | Joan | programmer | 23 Rock St | 1001 | 1.00 || 1003 | Bill | manager | 37 Front St | 1001 | 1.00 || 1001 | Fred | programmer | 13 Windle St | 1003 | 7.00 || 1002 | Joan | programmer | 23 Rock St | 1003 | 7.00 || 1003 | Bill | manager | 37 Front St | 1003 | 7.00 || 1001 | Fred | programmer | 13 Windle St | 1003 | 9.50 || 1002 | Joan | programmer | 23 Rock St | 1003 | 9.50 || 1003 | Bill | manager | 37 Front St | 1003 | 9.50 |+------------+------+------------+--------------+------------+-------+21 rows in set (0.01 sec)

The cartesian product query is rarely what we want.

Page 47: Lecture 11 Introduction to  Relational Database

47

Select Queries With Joins (3)• Substitution

+------+-------+| name | hours |+------+-------+| Fred | 13.50 || Joan | 2.00 || Joan | 6.25 || Bill | 4.00 || Fred | 1.00 || Bill | 7.00 || Bill | 9.50 |+------+-------+7 rows in set (0.00 sec)

Here we are replacing the employeeID numbers in the jobs table by the employee's

name

SELECT name, hours FROM employees, jobs WHEREemployees.employeeID = jobs.employeeID;

Page 48: Lecture 11 Introduction to  Relational Database

48

Select Queries With Joins (4)

• Entries only for Fred

+------+-------+| name | hours |+------+-------+| Fred | 13.50 || Fred | 1.00 |+------+-------+2 rows in set (0.00 sec)

SELECT name, hours FROM employees, jobs WHEREemployees.employeeID = jobs.employeeID ANDname = 'Fred';

Page 49: Lecture 11 Introduction to  Relational Database

49

Select Queries With Joins (5)• Total hours worked for each person

+------+------------+| name | SUM(hours) |+------+------------+| Bill | 20.50 || Fred | 14.50 || Joan | 8.25 |+------+------------+3 rows in set (0.00 sec)

SELECT name, SUM(hours) FROM employees, jobsWHERE employees.employeeID = jobs.employeeIDGROUP BY name;

Page 50: Lecture 11 Introduction to  Relational Database

Viewing The Table Structure

mysql> DESCRIBE students;

+------------+-------------+------+-----+---------+----------------+| Field | Type | Null | Key | Default | Extra |+------------+-------------+------+-----+---------+----------------+| num | int(11) | NO | PRI | NULL | auto_increment || f_name | varchar(48) | YES | | NULL | || l_name | varchar(48) | YES | | NULL | || student_id | int(11) | YES | | NULL | || email | varchar(48) | YES | | NULL | |+------------+-------------+------+-----+---------+----------------+

50

Page 51: Lecture 11 Introduction to  Relational Database

Example: data_in.php

Page 52: Lecture 11 Introduction to  Relational Database

Putting data into DatabaseStudent Database: data_in.php

<html><head><title>Putting Data in the DB</title></head><body><?php /*insert students into DB*/if(isset($_POST["submit"])) { $db = mysql_connect("mysql”, ”CSE382"); mysql_select_db("CSE382");

$date=date("Y-m-d"); /* current date in the right format */

$sql="INSERT INTO students VALUES(NULL,'“ . $_POST[“f_name"] . "','“ . $_POST["l_name"] . "',“ . $_POST["student_id"] . ",'“ . $_POST["email"] . "','“ . $date . "',“ . $_POST["gr"] . ")"; /* construct the query */

mysql_query($sql); mysql_close();

echo"<h3>Thank you. The data has been entered.</h3> \n"; echo'<p><a href="data_in.php">Back to registration</a></p>‘ .

“\n”; echo'<p><a href="data_out.php">View the student

lists</a></p>‘ .”\n”; }

52

Page 53: Lecture 11 Introduction to  Relational Database

Student Database: data_in.phpelse {?> <h3>Enter your items into the database</h3><form action="data_in.php" method="POST">First Name: <input type="text" name=“f_name“ /> <br/>Last Name: <input type="text" name=“l_name“ /> <br/>ID: <input type="text" name=“student_id“ /> <br/>email: <input type="text" name=“email“ /> <br/>Group: <select name="gr"> <option value ="1">1</option> <option value ="2">2</option> <option value ="3">3</option> <option value ="4">4</option> </select><br/><br/><input type="submit" name="submit“ /> <input type="reset“ /></form><?php }?></body></html>

53

Page 54: Lecture 11 Introduction to  Relational Database

Example data_out.php

Page 55: Lecture 11 Introduction to  Relational Database

Getting Data Out from DatabaseStudent Database: data_out.php

<html><head><title>Getting Data out of the DB</title></head><body><h1> Student Database </h1><p> Order the full list of students by <a href="data_out.php?order=date">date</a>,<href="data_out.php?order=student_id">id</a>, orby <a href="data_out.php?order=l_name">surname</a>.</p><p><form action="data_out.php" method="POST">Or only see the list of students in group <select name="gr"> <option value ="1">1</option> <option value ="2">2</option> <option value ="3">3</option> <option value ="4">4</option></select><br/><input type="submit" name="submit“ /></form></p>

55

Page 56: Lecture 11 Introduction to  Relational Database

Student Database: data_out.php

<?php /*get students from the DB */$db = mysql_connect("mysql",“CSE382");mysql_select_db(“CSE382", $db);

switch($_GET["order"]){case 'date': $sql = "SELECT * FROM students ORDER BY date"; break;case ‘student_id': $sql = "SELECT * FROM students ORDER BY student_id"; break;case ‘l_name': $sql = "SELECT * FROM students ORDER BY l_name"; break;default: $sql = “SELECT * FROM students”; }if(isset($_POST["submit"])){ $sql = “SELECT * FROM students WHERE gr=“ . $_POST["gr"];}

$result=mysql_query($sql);while($row=mysql_fetch_array($result)){ echo "<h4> Name: “ . $row["l_name"] . ', ‘ . $row["f_name"] . "</h4> \n"; echo "<h5> ID: “ . $row[“student_id"] . "<br/> Email: “ . $row["email"] .

"<br/> Group: “ . $row["gr"] . "<br/> Posted: “ . $row["date"] . "</h5> \n";}mysql_free_result($result);mysql_close();?></body></html>

56

Page 57: Lecture 11 Introduction to  Relational Database

57

Poll Example

• Simple form that gives a list of choices for the poll

• Save poll results in a database• Don't allow user to do the poll more than

once from the same URL• Include a "show results" button that gives the

percentages for each entry in the list of choices

Page 58: Lecture 11 Introduction to  Relational Database

58

Poll Results Database Table

CREATE TABLE poll_results( votes INT UNSIGNED NOT NULL DEFAULT 0, yes INT UNSIGNED NOT NULL DEFAULT 0);INSERT INTO poll_results VALUES(0,0);

This table keeps track of the total number ofvotes and the total number of yes votes

Page 59: Lecture 11 Introduction to  Relational Database

59

IP Address Database Table

CREATE TABLE poll_ips( ip VARCHAR(30) NOT NULL, PRIMARY KEY (ip));

When a user votes the IP addressis stored in this table so that nonefrom this location can vote again

Page 60: Lecture 11 Introduction to  Relational Database

60

Voting Displaysdisplay after

voting

display after trying to vote

again

Page 61: Lecture 11 Introduction to  Relational Database

61

Script LogicOpen a database connectionGet user IP addressIF results button was clicked THEN display the poll resultsELSE IF submit button clicked AND vote entered THEN Get the vote from radio button IF user has already voted THEN Warn user ELSE submit the vote ENDIF display the poll resultsELSE display the poll voting formENDIFClose the connection

Page 62: Lecture 11 Introduction to  Relational Database

62

poll.php (1)<?phprequire_once("db_connect.php");start_html();$ip_address = $_SERVER['REMOTE_ADDR'];$poll_question = "Do you like Java programming?";

// Table for ip addresses

$ip_table = "poll_ips";// Table for total votes and total yes votes

$vote_table = "poll_results";$db_link = db_connect("web_db");

Page 63: Lecture 11 Introduction to  Relational Database

63

poll.php (2)if (isset($_REQUEST['results'])){ display_poll_results($poll_question, $vote_table);}elseif ( isset($_REQUEST['submit']) && isset($_REQUEST['vote']) ){ $vote = $_REQUEST['vote']; if ( has_voted($ip_address, $ip_table) ) { echo '<p class="warn">Someone at your location has already votes</p>'; }

Page 64: Lecture 11 Introduction to  Relational Database

64

poll.php (3) else { submit_poll_vote($ip_address, $vote, $vote_table, $ip_table); } display_poll_results($poll_question, $vote_table);else{ display_poll_form($poll_question);}mysql_close($db_link);end_html();exit(0);

Page 65: Lecture 11 Introduction to  Relational Database

65

poll.php (4)function start_html(){?><html><head><title>Web Poll using MySQL</title> <style type="text/css"> .warn {font-weight: bold; font-size: small; color: #FF0000 } .bg1 { background-color: #AEC6D9 } .bg2 { background-color: #0099CC } </style></head><body><?php}

Page 66: Lecture 11 Introduction to  Relational Database

66

poll.php (5)function end_html(){ ?> </body> </html> <?php}

Page 67: Lecture 11 Introduction to  Relational Database

67

poll.php (6)

function has_voted($user_ip, $ip_table){ // return false // comment when testing is complete

$query = "SELECT ip FROM $ip_table WHERE ip = '$user_ip'"; $result = mysql_query($query) or die("CheckIP query failed"); return mysql_num_rows($result) > 0;}

Page 68: Lecture 11 Introduction to  Relational Database

68

poll.php (7)

function display_poll_form($poll_question){ $script_url = $_SERVER['PHP_SELF']; ?> <h2>Poll Question</h2> <h3><?php echo $poll_question?></h3> <form method="POST" action= "<?php echo $script_url ?>"> <input type="radio" name="vote" value=1 />Yes<br /> <input type="radio" name=vote" value=0 />No<br /> <input type="submit" name="submit" value="Submit"/> <input type="submit" name="results value="Results"/> </form> <?php}

Page 69: Lecture 11 Introduction to  Relational Database

69

poll.php (8)

function display_poll_results($poll_question, $vote_table){ $total_votes = 0; $total_yes = 0; $total_no = 0; $percent_yes = 0; $percent_no = 0; $query = "SELECT votes, yes FROM $vote_table"; $result = mysql_query($query) or die("Query failed"); if ( mysql_num_rows($result) == 1 ) { $row = mysql_fetch_assoc($result); $total_votes = $row['votes']; $total_yes = $row['yes']; $total_no = $total_votes - $total_yes; }

Page 70: Lecture 11 Introduction to  Relational Database

70

poll.php (9)

if ($total_votes != 0) { $percent_yes = round( (($total_yes / $total_votes)*100), 1); $percent_no = round( (100 - $percent_yes), 1); }

Page 71: Lecture 11 Introduction to  Relational Database

71

poll.php (10)

?> <h2>Poll Results</h2> <table border="0" cellpadding="5"> <tr> <td class="bg2" colspan="3"><b> <?php echo $poll_question ?></b></td> </tr>

Page 72: Lecture 11 Introduction to  Relational Database

72

poll.php (11) <tr> <td class="bg1">Yes</td> <td class="bg1"><?php echo $percent_yes ?> % </td> <td class="bg1"><?php echo $total_yes ?> votes </td> </tr> <tr> <td class="bg1">No</td> <td class="bg1"><?php echo $percent_no ?> %</td> <td class="bg1"><?php echo $total_no ?> votes </td> </tr> </table> <p><a href="seeit.php">View Source</a></p> <?php mysql_free_result($result);}

Page 73: Lecture 11 Introduction to  Relational Database

73

poll.php (13)

function submit_poll_vote($user_ip, $user_vote, $vote_table, $ip_table){ $total_votes = 0; $total_yes = 0;

// Get the current total votes and total yes vote

$query = "SELECT votes, yes FROM $vote_table"; $result = mysql_query($query) or die("Query failed");

Page 74: Lecture 11 Introduction to  Relational Database

74

poll.php (14)

if ( mysql_num_rows($result) == 1 ) { $row = mysql_fetch_assoc($result); $total_votes = $row['votes']; $total_yes = $row['yes']; } else // initialize the poll { $query = "INSERT INTO $vote_table SET votes = '0', yes ='0'"; $result = mysql_query($query) or die("<p>Query failed</p>"); }

Page 75: Lecture 11 Introduction to  Relational Database

75

poll.php (15)

// Update total votes and total yes votes $total_yes = $total_yes + $user_vote; // 1 = yes $total_votes++; $query = "UPDATE $vote_table SET votes = '$total_votes', yes = '$total_yes'"; $result = mysql_query($query) or die("<p>Update vote failed</p>\n");

// Record the browser ip so user can only vote once $query = "INSERT INTO $ip_table SET ip = '$user_ip'"; $result = mysql_query($query) or die("<p>Insertion of ip failed</p>\n");}

Page 76: Lecture 11 Introduction to  Relational Database

76

Authentication with MySQL

• Instead of using basic authentication that is implemented using HTTP headers it is better to use a database to store user names and passwords.

• A session variable can be used to identify a valid user.

• First create a data base with fields for the user id and the password:

Page 77: Lecture 11 Introduction to  Relational Database

77

login.sql (user database)

USE web_db;DROP TABLE IF EXISTS login;

CREATE TABLE login( name VARCHAR(10) NOT NULL, password VARCHAR(30) NOT NULL, PRIMARY KEY (name));# insert a few users and encrypt the passwords

INSERT INTO login VALUES ('test', PASSWORD('123'));INSERT INTO login VALUES ('look', PASSWORD('kool'));INSERT INTO login VALUES ('Fred', PASSWORD('Jones'));

Page 78: Lecture 11 Introduction to  Relational Database

78

user database

mysql> use web_db;Database changedmysql> SELECT * FROM login;+------+------------------+| name | password |+------+------------------+| test | 773359240eb9a1d9 || look | 7d74a0bb51520618 || Fred | 64099a8d551f7d81 |+------+------------------+3 rows in set (0.00 sec)mysql>

Page 79: Lecture 11 Introduction to  Relational Database

79

Login script logic

Start a sessionIF username AND password were submitted THEN Check that these values are alphanumeric. IF not THEN set them to empty strings END IF IF there is a matching row in login table THEN Set a 'valid-user' session variable having value the username as value. ELSE Display login page with form to login ENDELSE Display login page with form to loginEND

Page 80: Lecture 11 Introduction to  Relational Database

80

login.php (1)<?phprequire_once("db_connect.php");session_start();if (isset($_REQUEST['userid'] && isset($_REQUEST['password'])){ // Check for alphanumeric values

$id = ereg("^[a-zA-Z0-9]+$", $_REQUEST['userid']) ? $_REQUEST['userid'] : ""; $pass = ereg("^a-zA-Z0-9]+$",$_REQUEST['password']) ? $_REQUEST['password'] : "";

// now try to authenticate these values

Page 81: Lecture 11 Introduction to  Relational Database

81

login.php (2) if (isAuthentic($id, $pass)) { $_SESSION['valid_user'] = $id; display_members_page(); } else { display_login_page("Invalid login, try again"); }else // first time so display form to login{ display_login_page("Please log in");}?>

Page 82: Lecture 11 Introduction to  Relational Database

82

login.php (3)<?phpfunction isAuthentic($id, $password){ $db_link = db_connect("web_db");

$query = "SELECT * FROM login WHERE name like '$id'" . "AND password like PASSWORD('$password')";

$result = mysql_query($query, $db_link); $valid = mysql_num_rows($result) > 0;

mysql_free_result($result); mysql_close($db_link); return $valid;}?>

Page 83: Lecture 11 Introduction to  Relational Database

83

login.php (4)<?phpfunction display_login_page($message){?><html><head><title>Members Login Page</title></head><body><h1>Login Page</h1><h2><?php echo $message ?></h2><form method="POST"><table border="1"><tr><td>

Page 84: Lecture 11 Introduction to  Relational Database

84

login.php (5) <table border="0"> <tr><td>User Name:</td> <td><input type="text" name="userid"></td</tr> <tr><td>Password:</td> <td><input type="password" name="password"></td> </tr> <tr><td colspan=2 align=center> <input type="submit" value="Log in"></td></tr> </table></td></tr></table></form></body></html><?php}?>

Page 85: Lecture 11 Introduction to  Relational Database

85

login.php (6)<?phpfunction display_members_page(){?><html><head><title>Members Page</title></head><body>You have successfully logged in as user<strong><?php echo $_SESSION['valid-user']?></strong><p><a href="members.php?<?php echo SID?>">Memberpages</a><br><a href="logout.php?<?php echo SID?>">Logout</a></p></body></html><?php } ?>

Page 86: Lecture 11 Introduction to  Relational Database

86

logout.php<?phpsession_start();unset($_SESSION['valid-user']);session_destroy();?><html><head><title>Logout Page</title></head><body><h1>Logout Page</h1>If you were logged in you have been logged out<p><a href="login.php">Login Again</a></p></body></html>

Page 87: Lecture 11 Introduction to  Relational Database

87

members.php (1)<?phpsession_start();if (! isset($_SESSION['valid-user'])){ ?><html><head><title>Login Error</title></head><body><h1>Login Error</h1>You are not authorized to view this page, please <a href="login.php?<?php echo SID?>">login</a></body></html><?phpexit();}?>

Page 88: Lecture 11 Introduction to  Relational Database

88

members.php (2)<html><head><title>Member Page</title></head><body><h1>Member Page</h1>This is a member page.<br>You are logged in as user<strong><?php echo $_SESSION['valid_user']?></strong>.<p><a href="logout.php?<?php echo SID?>">Logout</a></p></body></html>

Page 89: Lecture 11 Introduction to  Relational Database

89

Some SQL data types (1)

• Each entry in a row has a type specified by the column.

• Numeric data types– TINYINT, SMALLINT, MEDIUMINT,– INT, BIGINT– FLOAT(display_length, decimals)– DOUBLE(display_length, decimals)– DECIMAL(display_length, decimals)

• NUMERIC is the same as DECIMAL

Page 90: Lecture 11 Introduction to  Relational Database

90

Some SQL data types (2)

• Date and time types– DATE

• format is YYYY-MM-DD

– DATETIME• format YYYY-MM-DD HH:MM:SS

– TIMESTAMP• format YYYYMMDDHHMMSS

– TIME• format HH:MM:SS

– YEAR• default length is 4

Page 91: Lecture 11 Introduction to  Relational Database

91

SQL data types (3)

• String types– CHAR

• fixed length string, e.g., CHAR(20)

– VARCHAR• variable length string, e.g., VARCHAR(20)

– BLOB, TINYBLOB, MEDIUMBLOB, LONGBLOB

• same as TEXT, TINYTEXT ...

– ENUM• list of items from which value is selected

Page 92: Lecture 11 Introduction to  Relational Database

Design Report Outline• Preface • Introduction• Detail about the company and work process• Detail about the system you will be working• System Specification & User Requirement• System Models: Use Case, Sequential diagram, Data Flow diagram, UML,

Structured Chart• Data Modeling: Database requirement, ER-Diagram, Empty tables, Relational

Schema Diagram• User Interface Design• Conclusion• Bibliography• Appendices: HW, DB, logical organization• Index: index of diagrams, Tables, Functions etc.

Page 93: Lecture 11 Introduction to  Relational Database