Download presentation
Presentation is loading. Please wait.
Published byJustin Jacobs Modified over 6 years ago
1
Advanced Higher Computing Science Database Systems and SQL
Welcome to the fourth online Advanced Higher session.
2
In this session we will look at relational database systems and how they can be managed using the Standard Query Language (SQL)
3
Content What is a Relational Database? Entity Relationship Diagrams Online database systems Using PHP and SQL to query and manage an online database Structured Query Language (SQL) SQL syntax, commands and functions Past paper questions
4
What is a Relational Database?
A relational database is a database which contains more than one linked table. Every table should have a unique primary key. This key can be used to link to other tables in the database where it appears as a foreign key. Using more than one table avoids the unnecessary duplication of information which would be necessary if a single flat file database was used and reduces the overall file size. Since specific data is only stored in one table, changing it in that table will change it in all the linked tables.
5
Preparation question 1 A food outlet information system contains details of the products and their suppliers. Part of the data dictionary for the Product entity is shown below: Identify the Primary key and Foreign key in the above table and state the associated value for the Unique column for these keys. PK Y A bit of revision here FK N
6
Relational Database Example
cust_id and product_id are foreign keys in the mapping table.
7
Entity-Relationship Diagrams
Themapping table is used to connect the customer and products tables Cust_id and Procuct_id are not unique when they are foreign keys cust_id* product_id* Customer Product Sale (mapping table There is a many to many relationship between Customers and Products
8
Online Relational Database Systems
Online database systems use a database server which can be queried by a client system using an appropriate query language. The user will usually be presented with an HTML form to construct their query. The contents of the form are passed to a PHP script which then uses this to query the database using the SQL query language. The results of the query is passed to the client where they are usually presented in a readable format, often using another HTML form. Typical software used are a client browser, an Apache web server running PHP and a database server running MySQL
9
Online Relational Database Systems
Advanced Higher Computing Science Unit 2 Topic 5.2.1 HTML result HTML result (other database technologies are available)
10
User requests a web page that contains a form.
HTML Forms: User (client) view User requests a web page that contains a form. Web browser displays the HTML form. REPEAT User completes the form and submits it. IF any required fields are empty or fields are not the required format THEN User is informed of error. UNTIL fields contain correct data. Web browser displays response page. Note – the repeat until loop validation can be done using HTML code or client side scripting. Why important that this is done client side?
11
User requests HTML page containing a form.
HTML forms: server view User requests HTML page containing a form. Server sends form page to client. Form data is received from client browser. Form data is processed by script and passed to database server. Database is queried/updated. Web server sends database server response to client and page content is updated. Validated form data is sent to server which uses server side scripting to process it. NB both web server and database server are needed here.
12
appends form data into the URL in name/value pairs (delimitated by &);
Sending form data to a server-side script: GET The values from the form are visible in the URL so are insecure. The string on values starts with "?" appends form data into the URL in name/value pairs (delimitated by &); the length of a URL is limited (to roughly 3000 characters); not suitable for sensitive information because the data is visible in the URL; useful for instances where the data will be part of a bookmark/link to a page; useful when debugging because the values passed to the processing script are visible. Eg a simple search form
13
adds the form data to the HTTP request to the processing script
Sending form data to a server-side script: POST The POST method adds the form data inside the body of the HTTP request to the processing script so the data is not visible in the URL. This is generally more secure than the GET method. adds the form data to the HTTP request to the processing script has no size limitations on the amount of data that can be submitted form submissions with POST cannot be bookmarked Where you need to send data to a secure database
14
Sending form data to a database
<form name="addData" method="POST" action="addData.php"> <label for="forename">Enter your forename here</label> <input type="text" name="forename" /> <label for="surname">Enter your surname here</label> <input type="text" name="surname" /> <input type="submit" name="submit" value="Submit" /> </form> Two possible methods are available: GET and POST The GET method adds the list of values from the form to the URL of the processing script. The POST method adds the form data inside the body of the HTTP request to the processing script so the data is not visible in the URL. This is generally more secure than the GET method. The action is the name of the script which processes the data
15
The addData.php script <?php //get data from form
$forename = $_POST['forename']; $surname = $_POST['surname']; //connect to mysql server $mysqli = new mysqli( "server" , "username" , "password", "database"); //SQL code to add data to database $sqlQuery ="INSERT INTO users (forename, surname)VALUES ('$forename','$surname')"; $result = $mysqli->query($sqlQuery); print "update successful" ?> Data sent from the form is added to the database
16
PHP (Hypertext Preprocessor)
A server-side scripting language PHP code is always enclosed inside this tag: <?php ?> PHP variable names are prefixed with a $ symbol Every statement must end with a semicolon ";" Comments start with // Some very basic PHP syntax
17
Retrieving data from the database
<?php //connect to mysql server $mysqli = new mysqli( "server" , "username" , "password", "database"); // setting up the MySQL query $sqlquery = "SELECT * FROM users"; $result = $mysqli -> query($sqlquery); // get data //setting up table and printing two column headings print "<table width = 50% border=1>"; print"<tr><td><b>Forename</b></td><td><b>Surname</b></td></tr>"; //while there is data to retrieve while ( $db_field = mysql_fetch_assoc($result) ) { //print row with two cells print "<tr> <td>"; print $db_field['forename']. "</td><td>"; print $db_field['surname']. "</td></tr>"; } print"</table>"; ?>
18
Form security: Code Injection
This attack is when a weakness in poorly written code is used by an attacker to inject code into a vulnerable script and change the execution of the script. Attackers will paste SQL or HTML code into a web form to extract unauthorised data from the database or control the MySQL server.
19
Server-side validation: sanitization
Sanitization is the removal of illegal characters from the form data, to protect against code injection attacks $name =filter_var($_GET['name'],FILTER_SANITIZE_STRING);
20
Server-side validation: sanitization
© XKCD
21
Server-side validation: PHP validation
function validate_form ($username, $ ) { if(!ctype_alnum($username)||!filter_var($ , FILTER_VALIDATE_ )){ return false; } return true; This function uses the PHP type ctype_alnum to validate the username because this requires that $username be alphanumeric only. The PHP filter. FILTER_VALIDATE_ is used for the address. Should either of these be invalid then a value of false is returned from the function. If they are valid then true is returned.
22
Structured Query Language (SQL)
CREATE DATABASE CREATE TABLE USE DELETE SELECT ORDER BY GROUP BY CASCADE INSERT INTO UPDATE SET SQL Syntax Keywords are in upper case. Statements end with a semi colon. ;
23
SQL commands: CREATE, USE
CREATE DATABASE database_name ; USE database_name; CREATE TABLE table1 ( field1 data_type(size) NOT NULL PRIMARY KEY, field2 data_type(size), field3 data_type(size), ) ; NOT NULL means that the field is required Data Types VARCHAR: A variable-length string. INT: Integer REAL: Floating point number TEXT: text, max length 65535 characters DATE: TIME:
24
SQL commands: foreign keys
CREATE TABLE table_2 ( field4 INT AUTO_INCREMENT NOT NULL PRIMARY KEY, field5 VARCHAR(35) NOT NULL, // using primary key field1 from table_1 as a foreign key in table_2 // FOREIGN KEY (field1) REFERENCES table_1 (field1) ON UPDATE CASCADE ON DELETE CASCADE ); ON UPDATE CASCADE means that if the value of the primary key in referenced table were to change, then all related values in this table would also change. ON DELETE CASCADE means that if a primary key row was deleted, then all related foreign key records in this table would also be deleted
25
SQL commands: INSERT, UPDATE
INSERT INTO customer_table (cust_no, name, address) VALUES ('134', 'Fred Flintstone', 'Bedrock'), ('241', 'Barney Rubble', 'Bedrock'); UPDATE customer_table SET address = '1 Slate Road, Bedrock' WHERE cust_no = '134';
26
SQL Commands: operators used with WHERE
Simple condition: WHERE field operator 'value'; = >= > < != LIKE (can use wildcard %) IS NOT NULL Complex condition: WHERE field operator 'value' operator field operator 'value' AND (&&) OR (| |) Where cost > 200 Where cost > 200 AND discount = TRUE
27
SQL Commands: DELETE, SELECT
DELETE FROM table_name WHERE field_column = search_value; DELETE FROM customer_table WHERE cust_no = '241'; SELECT cust_no, name, address FROM customer_table WHERE address = 'Bedrock' ORDER BY cust_no ASC; Use ASC or DEC depending on how you want the data to be sorted
28
SQL Commands: Aggregate functions
SELECT function (field) FROM table; COUNT number of rows in table SUM total value of entries in field MAX maximum value in field MIN minimum value in field AVG average value of entries in field SELECT COUNT(*) FROM customer_table WHERE address LIKE 'Bedrock'
29
SQL Commands: equi-join
An equi-join is a basic join with a WHERE clause that contains a condition specifying that the value in one column in the first table must be equal to the value of a corresponding column in the second table. SELECT * FROM table1, table2 WHERE table_1.field1 = table_2.field1;
30
SQL Commands: equi-join
A query to list the products associated with customer ID 1 requires all 3 tables to be related using an equi-join Previous database example
31
SQL Commands: equi-join
The SQL view of the query uses the INNER JOIN (a subset of the EQUI JOIN) SELECT products.product_id, products.name FROM products INNER JOIN (Customer INNER JOIN mapping ON Customer.[cust_id] = mapping.[cust_id]) ON products.[product_id] = mapping.[product_id] WHERE (((Customer.cust_id)=1));
32
Preparation question 2 An information system contains the following tables: ATHLETE(athleteID, firstname, surname, DOB, country) COUNTRY(country, continent, number of medals) A sports commentator uses the system to find information about athletes. Write the SQL code to display the number of Scottish athletes. SELECT COUNT(*) FROM athlete WHERE country = ‘Scotland’; Write the code to execute this script using a server-side scripting language. $connection = mysql_connect($server, $username, $password); $query = (‘SELECT count(*) FROM athlete WHERE country = ‘Scotland’’); mysql_query($connection,$query);
33
Preparation question 3 Server side scripting is used to extract the data from a database table called hillruns. The contents of the hillruns table are shown below. Write an SQL query to show all runs with the trackname ‘Pentlands Run’, sorted into order of timemins, with quickest run listed first. SELECT trackname, rundate, timemins FROM hillruns WHERE trackname ='Pentlands Run' ORDER BY timemins;
34
2017 Q2 2016 Q2 Specimen Paper Q2 Exemplar Paper Q2
Past Paper Questions 2017 Q2 2016 Q2 Specimen Paper Q2 Exemplar Paper Q2 2015 Information Systems Q13
35
2017 Q2a A restaurant chain wants a new app which will allow registered users to make reservations for restaurants that are part of the chain. All users must register before they can use the app for the first time. A development team is asked to create the new app. (a) The developers begin by designing an SQL table called RegUser. This table will be used to store the details of all of the registered users. The table will be stored in a relational database called RestaurantApp. The RegUser table will store a userID which is automatically created, the user’s title, first name and last name, a phone number for contact purposes and a password. Users will be asked to provide all of these details when they register.This data will be captured using the HTML form shown. The userID will be generated automatically by the database server when a new record is added to the table. Data values must be provided for all fields marked *. Copy and complete the two lines of the data dictionary below to show the structure of the SQL table called RegUser for the fields listed. Your data dictionary should indicate appropriate SQL data types. Field Key Type/Size Constraints/Validation userID title Primary (Surrogate) Key INT NOT NULL auto increment VARCHAR (4) / TEXT (4) = Mr || MRs || Miss || Ms
36
2017 Q2b The HTML script used to generate the registration form is provided below.
37
2017 Q2b The submit button on the form is used to submit the registration data to a server-side script. This script is used to connect to the database server and add the registration details to the RegUser table of the RestaurantApp database. The RegUser table has 6 fields: userID, title, firstName, lastName, contactNo and password. The connection details used are: server name: sn001 user: anon001 password: ap001 Using a server-side scripting language with which you are familiar, write the script used to connect to the database server. The script should: (i) assign the registration details to server-side variables (ii) create a connection to the database server (iii) execute the SQL query used to add the registration details to the RegUser table.
38
2017 Q2b The RegUser table has 6 fields: userID, title, firstName, lastName, contactNo and password. (i) assign the registration details to server-side variables <?php $title = $_POST['Item1']; $firstname = $_POST['Item2']; $lastname = $_POST['Item3']; $phone = $_POST['Item4']; $password = $_POST['Item5']; $servername = "sn001"; $username = "anon001"; $password = "ap001; $database="RestaurantApp"; $connection = mysql_connect($server, $username, $password); mysql_select_db($database,$connection); $query = "INSERT INTO RegUser (Title, FirstName, LastName, PhoneNo, Password) VALUES ('$Title','$firstname', '$lastname', '$phone', '$password'); mysql_query($connection, $query); mysql_close($connection); ?> (ii) create a connection to the database server (iii) execute the SQL query used to add the registration details to the RegUser table.
39
2017 Q2c Details of restaurant reservations will be stored in the relational database in a separate table called Reservation. Part of the Reservation table is shown below. Relationships RegUser: Reservation 1:M The RegUser table has 6 fields: userID, title, firstName, lastName, contactNo and password. The manager of each restaurant needs a list of reservations made for the day. Write an SQL statement to display a list of all reservations for restaurant 1 on the 1st of July The list should show the first name, last name and title for each reservation, the time of the reservation and the size of each group. The reservation details should be displayed so that the earliest reservation for the restaurant is listed first.
40
2017 Q2c RegUser Reservation
SELECT title, firstname, lastname, time, sizeofparty FROM RegUser, Reservation WHERE RegUser.userID = Reservation.regUserID AND date="07/01/2017" AND restaurantID = 1 ORDER BY time ASC; The list should show the first name, last name and title for each reservation, the time of the reservation and the size of each group. a list of all reservations for restaurant 1 on the 1st of July 2017. The earliest reservation for the restaurant should be listed first.
41
2016 Q2c A PlayList table is used to store details of all playlists created by Radio Lowden and details of each song are stored in a separate table called Song. These tables are part of a relational database. Sample data for the PlayList and Song tables are shown. Write the SQL statement which will create the structure of the PlayList table. CREATE TABLE PlayList ( ProgrammeID INT NOT NULL, SongID TEXT(6) NOT NULL, DatePlayed DATE NOT NULL, TimePlayed TIME NOT NULL, PRIMARY KEY (Dateplayed, Timeplayed), FOREIGN KEY (SongID) REFERENCES Song(SongID) ); NB other primary keys are possible
42
2016 Q2c Write the SQL query which will list the title of each song played on 26 May SELECT Title FROM PlayList, Song WHERE PlayList.SongID =Song.SongID AND DatePlayed = '2016/05/26';
43
Specimen Paper Q2b Details of the Customers, BiskitBoxes and Orders will be stored in the following four relations: Customer(CustomerRef, CustomerName, Address, Postcode, ) BiskitBox(BoxCode, Description, Price, StockLevel) Order(OrderID, CustomerRef, OrderDate) OrderLine(OrderID, BoxCode, QuantityOrdered) Note: In this representation, the primary key of each relation has been underlined. When an order is placed, a customer-order process is initiated. This uses server-side script to display a summary of all items in the order. The summary should display only the BoxCode, Description, Price and QuantityOrdered, as shown below:
44
Specimen Paper Q2b Customer(CustomerRef, CustomerName, Address, Postcode, ) BiskitBox(BoxCode, Description, Price, StockLevel) Order(OrderID, CustomerRef, OrderDate) OrderLine(OrderID, BoxCode, QuantityOrdered) Write a SQL query that will extract the details needed to display the summary for OrderID 759. SELECT BoxCode, Description, Price, QuantityOrdered FROM BiskitBox, OrderLine WHERE OrderID = 759 AND BiskitBox.BoxCode = OrderLine.BoxCode; Write the SQL statement that must be added to your query to display the summary details in decreasing order of Price. ORDER BY Price DESC
45
Exemplar paper Q2 All motel and booking details are stored on a database server that stores the following tables: CUSTOMER (CustomerID, FirstName, LastName, ContactNumber, ) BOOKING (BookingID, ArrivalDate, Duration, CustomerID, NumberInParty, RoomID) ROOM (RoomID, Type, CostPerNight, Sleeps) The information system uses SQL to manipulate the database to store customer and booking data. Part of each table in the database is shown below.
46
Exemplar paper Q2 All motel and booking details are stored on a database server that stores the following tables: CUSTOMER (CustomerID, FirstName, LastName, ContactNumber, ) BOOKING (BookingID, ArrivalDate, Duration, CustomerID, NumberInParty, RoomID) ROOM (RoomID, Type, CostPerNight, Sleeps) A customer changes their contact number. Write the SQL statement required to amend the contact number for the customer with CustomerID 2212 to UPDATE Customer SET ContactNumber = ' ' WHERE CustomerID = 2212;
47
Exemplar paper Q2 CUSTOMER (CustomerID, FirstName, LastName, ContactNumber, ) BOOKING (BookingID, ArrivalDate, Duration, CustomerID, NumberInParty, RoomID) ROOM (RoomID, Type, CostPerNight, Sleeps) The following invoice is generated when a customer checks out. Write the SQL statement to generate the data required for the invoice for the customer with BookingID SELECT BookingID, FirstName, LastName, ArrivalDate, Duration, CostPerNight, [Duration]*[CostPerNight] FROM Customer, Booking, Room WHERE (Customer.CustomerID=Booking.CustomerID) AND (Booking.RoomID=Room.RoomID) AND (Booking.CustomerID=2212);
48
Exemplar paper Q2 CUSTOMER (CustomerID, FirstName, LastName, ContactNumber, ) BOOKING (BookingID, ArrivalDate, Duration, CustomerID, NumberInParty, RoomID) ROOM (RoomID, Type, CostPerNight, Sleeps) Staff use the database to send customers information about special events happening during their stay. Write the SQL query to display the full name and address of all customers arriving at the motel on 31 December. SELECT FirstName, LastName, FROM Customer, Booking WHERE Customer.CustomerID = Booking.CustomerID AND ArrivalDate = '31/12/2015';
49
2015 Information Systems Q13 A database is used to store details of the tents for sale in a camping shop. Contents of the comment table are shown below: Write an SQL query to find the average rating for each tent. SELECT comment.tentid, AVG (comment.rating) FROM comment GROUP BY comment.tentid;
50
2015 Information Systems Q13 The following tent in the tent table has been discontinued and its record is to be removed from the database. Write an SQL query which would remove this record. SELECT comment.tentid, AVG (comment.rating) DELETE FROM tent WHERE tentid = 0005;
51
Just close your app/browser to leave the session.
If you have any questions on tonight’s session please ask. You will find the recording of this and all the other sessions on SCHOLAR. Please leave us feedback on tonight’s session: Just close your app/browser to leave the session. Thank you for taking part. This was the last Advanced Higher online session this year.
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.