Lecture 10 - Introduction to Relational Database

advertisement
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
 MySql Functions
Client-Server Interaction
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.


Make a request
(SQL query)
MySQL
Server
3
Get results
Client
Program
3-Tier Architecture
Web
Browser
(Client)
Web
Server
PHP
Database
Server
4
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
Program
Program
Program
Program
Data
Data
Data
Database
DBMS
5
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
name
attributes
6
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
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
8
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;
9
Entering commands (1)
• Show all the databases
– SHOW DATABASES;
mysql> SHOW DATABASES;
+-------------+
| Database
|
+-------------+
| bookstore
|
| employee_db |
| mysql
|
| student_db |
| test
|
| web_db
|
+-------------+
10
Entering commands (2)
• Choosing a database and showing its tables
– USE test;
SHOW tables;
mysql> USE test;
Database changed
mysql> SHOW tables;
+----------------+
| Tables_in_test |
+----------------+
| books
|
| name2
|
| names
|
| test
|
+----------------+
4 rows in set (0.00 sec)
mysql>
11
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>
12
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
13
Example of SQL DDL
studentID
first_name
last_name
mark
marks
table
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)
);
14
marks.sql
-- Insert some rows into marks table
INSERT 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);
15
Conditional Creation
• Conditional database creation
– CREATE DATABASE IF NOT EXISTS
db_name;
• Conditional table creation
– CREATE TABLE IF NOT EXISTS
table_name;
16
Entering commands
• Selecting the complete table
SELECT * 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)
17
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
PHP to MySQL Connectivity
• 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.
19
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
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
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
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
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
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
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
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
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;
} ?>
28
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:
SELECT COUNT(id) FROM table_name
• Can also perform searching using the WHERE
option
29
MySQL Functions (1)
• How many rows are there ?
SELECT COUNT(*) FROM marks;
+----------+
| COUNT(*) |
+----------+
|
5 |
+----------+
1 row in set (0.00 sec)
• Can use COUNT(marks) instead of
COUNT(*)
30
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)
31
MySQL Functions (3)
• What is the average mark?
SELECT AVG(mark) FROM marks;
+-----------+
| AVG(mark) |
+-----------+
|
74.6000 |
+-----------+
1 row in set (0.00 sec)
32
MySQL Functions (4)
• What is the minimum mark?
SELECT MIN(mark) FROM marks;
+-----------+
| MIN(mark) |
+-----------+
|
60 |
+-----------+
1 row in set (0.00 sec)
33
MySQL Functions (5)
• What is the maximum mark?
SELECT MAX(mark) FROM marks;
+-----------+
| MAX(mark) |
+-----------+
|
86 |
+-----------+
1 row in set (0.00 sec)
34
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: 0
mysql> SELECT * FROM names;
+----+-----------+------------+
| id | firstName | lastName
|
+----+-----------+------------+
| 1 | Fred
| Flintstone |
| 2 | Barney
| Rubble
|
| 3 | Ralph
| Stone
|
+----+-----------+------------+
3 rows in set (0.00 sec)
mysql>
35
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 rows
of a table.
36
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)
37
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)
38
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)
39
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
40
Searching Using LIKE (2)
• Example: last names in marks table that begin
with J
SELECT * FROM marks WHERE last_name
LIKE 'J%';
• Example: first names that have 3 letters
SELECT * FROM marks WHERE first_name
LIKE '_ _ _';
41
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');
42
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);
43
Database Tables
Jobs table
Employees table
Employee_id
hours
1001
13.5
Rock St
1002
2
37 Front ST
1002
6.25
1003
4
1001
1
1003
7
1003
9.5
Employee_id
name
position
address
1001
Fred
Programmer
13 Windle St
1002
Joan
Programmer
1003
Bill
manager
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 |
45
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.
46
Select Queries With Joins (3)
• Substitution
SELECT name, hours FROM employees, jobs WHERE
employees.employeeID = jobs.employeeID;
+------+-------+
| 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)
47
Here we are replacing the
employeeID numbers in the
jobs table by the employee's
name
Select Queries With Joins (4)
• Entries only for Fred
SELECT name, hours FROM employees, jobs WHERE
employees.employeeID = jobs.employeeID AND
name = 'Fred';
+------+-------+
| name | hours |
+------+-------+
| Fred | 13.50 |
| Fred | 1.00 |
+------+-------+
2 rows in set (0.00 sec)
48
Select Queries With Joins (5)
• Total hours worked for each person
SELECT name, SUM(hours) FROM employees, jobs
WHERE employees.employeeID = jobs.employeeID
GROUP BY name;
+------+------------+
| name | SUM(hours) |
+------+------------+
| Bill |
20.50 |
| Fred |
14.50 |
| Joan |
8.25 |
+------+------------+
3 rows in set (0.00 sec)
49
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
Example: data_in.php
Putting data into Database
Student 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
Student Database: data_in.php
else {
?>
<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
Example data_out.php
Getting Data Out from Database
Student 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>, or
by <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
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
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
57
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 of
votes and the total number of yes votes
58
IP Address Database Table
CREATE TABLE poll_ips
(
ip VARCHAR(30) NOT NULL,
PRIMARY KEY (ip)
);
When a user votes the IP address
is stored in this table so that none
from this location can vote again
59
Voting Displays
display after
voting
60
display after
trying to vote
again
Script Logic
Open a database connection
Get user IP address
IF results button was clicked THEN
display the poll results
ELSE 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 results
ELSE
display the poll voting form
ENDIF
Close the connection
61
poll.php (1)
<?php
require_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");
62
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>';
}
63
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);
64
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
}
65
poll.php (5)
function end_html()
{
?>
</body>
</html>
<?php
}
66
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;
}
67
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
}
68
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;
}
69
poll.php (9)
if ($total_votes != 0)
{
$percent_yes = round( (($total_yes /
$total_votes)*100), 1);
$percent_no = round( (100 - $percent_yes), 1);
}
70
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>
71
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);
}
72
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");
73
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>");
}
74
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");
}
75
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:
76
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'));
77
user database
mysql> use web_db;
Database changed
mysql> SELECT * FROM login;
+------+------------------+
| name | password
|
+------+------------------+
| test | 773359240eb9a1d9 |
| look | 7d74a0bb51520618 |
| Fred | 64099a8d551f7d81 |
+------+------------------+
3 rows in set (0.00 sec)
mysql>
78
Login script logic
Start a session
IF 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
END
ELSE
Display login page with form to login
END
79
login.php (1)
<?php
require_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
80
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");
}
?>
81
login.php (3)
<?php
function 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;
}
?>
82
login.php (4)
<?php
function 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>
83
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
}
?>
84
login.php (6)
<?php
function 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?>">Member
pages</a><br>
<a href="logout.php?<?php echo SID?>">Logout</a>
</p>
</body></html>
<?php } ?>
85
logout.php
<?php
session_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>
86
members.php (1)
<?php
session_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>
<?php
exit();
}
?>
87
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>
88
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
89
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
90
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
91
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.
Download