Download presentation
Presentation is loading. Please wait.
Published byJohn Sparks Modified over 7 years ago
1
CMPE 180-38 Database Systems Workshop June 6 Class Meeting
Department of Computer Engineering San Jose State University Summer 2017 Instructor: Ron Mak
2
Teams? Ninja Titans Super Coder Ishwarya Varadarajan Avni Gulati
Kanika Gupta Rucha Apte Titans Mohammed Athar Rahil Modi Shikhar Gaur Super Coder Akinfemi Akin-Aluko Zihan Ke Xiaoran Lin Bou-Yu Chen
3
PHP Syntax Very similar to C. Case sensitive: Case insensitive:
End each statement with a semicolon. Case sensitive: variables, constants, array keys class properties and constraints Case insensitive: functions (pre-defined and user-defined) class constructors and methods reserved words
4
PHP Variables All variable names start with $.
PHP is a dynamically typed language. You don’t declare a variable’s data type. A variable can be assigned a value of any data type. PHP data types scalar: integer, float, boolean, string array object resource NULL
5
PHP Strings Enclose a string with single or double quotes.
Examples: Variables embedded in a double-quoted string are evaluated: But not: "Hello, world!" 'Hello, world!' "It's a nice day." 'Define "string" for me.' "Define \"string\" please." "The first name is $first." 'The first name is $first.'
6
PHP String Operations The string concatenation operator is .
Better: Some string functions: strlen() strtoupper() strtolower() ucwords() capitalize the first letter of every word $name = $last . ", " . $first; $name .= ", Esq."; $name = "$last, $first"; Demo
7
Heredocs Use a heredoc to avoid string quoting issues. Example:
$first = "John"; $last = "Smith"; print <<<HERE <table border="1"> <tr> <td>First name:</td> <td>$first</td> </tr> <td> Last name:</td> <td>$last</td> </tr></table> HERE; Must be on a line by itself with no indentation. Demo
8
PHP Constants Name constants with all uppercase letters, by convention. Constants are not variables, so do not use $. Examples But not: define (PI, ); define (HOST_NAME, "localhost"); print "Host name is " . HOST_NAME; print "Host name is HOST_NAME";
9
Two Kinds of PHP Arrays Indexed array Associative array
Indexes are integers. Associative array Indexes are strings. key-value pairs, like a hash table.
10
Creating PHP Indexed Arrays
$bands[] = "Beatles"; $bands[] = "Rolling Stones"; $bands[] = "Queen"; Use the array() function: Specify the first index value. Subsequent elements are indexed incrementally. An array of sequential numbers: $bands = array("Beatles", "Rolling Stones", "Queen"); $bands = array(2=>"Beatles", "Rolling Stones", "Queen"); $values = range(5, 10);
11
Creating PHP Associative Arrays
$states["CA"] = "California"; $states["NY"] = "New York"; $states["TX"] = "Texas"; Use the array() function: $states = array( "CA" => "California", "NY" => "New York", "TX" => "Texas" ); An associative array is like a hash table.
12
Looping over Array Elements
Use the foreach statement: Examples: foreach ($arrayname as $variable) { … } foreach ($arrayname as $key => $value) { … } foreach ($bands as $bandName) { print $bandName; } foreach ($states as $abbrev => $fullName) { print "State $fullName is abbreviated $abbrev"; } Demo
13
Multidimensional Arrays
$north = array("ND" => "North Dakota", "MN" => "Minnesota"); $south = array("TX" => "Texas", "FL" => "Florida"); $east = array("NY" => "New York", "ME" => "Maine"); $west = array("CA" => "California", "OR" => "Oregon"); $us = array( "N" => $north, "S" => $south, "E" => $east, "W" => $west );
14
Multidimensional Arrays, cont’d
print "<ul>\n"; foreach ($us as $region => $states) { print " <li>\n"; print " <h2>$region</h2>\n"; print " <ul>\n"; foreach ($states as $abbrev => $name) { print " <li>$abbrev: $name</li>\n"; } print " </ul>\n"; print "</ul>\n"; Demo
15
PHP Functions Syntax for programmer-defined functions:
Examples: A function can optionally return a value. function name (optional arguments) { // statements in the body } function doSomething() { … } function sayHello($first, $last) { … } function greet($name, $language = "English") { … } function calculate($input, &$output) { … } Default value Passed by reference return value;
16
Scope of PHP Variables Variables have the scope of the PHP file in which they reside. A programmer-defined function creates a scope for its variables. Variables defined in a function cannot be accessed outside the function. Variables defined outside the function are not accessible inside the function. Use the global statement inside a function to access outside variables. Example: global $outsideVar;
17
PHP Data Objects (PDO) Create a database abstraction layer:
Postgres MySQL Oracle PHP Data Objects (PDO) PHP query() PDO documentation:
18
PDO Examples // Connect to the database. $con = new PDO("mysql:host=localhost;dbname=supercoders", "supercoders", "sesame"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Create a new PDO object to represent the database connection. Set the error mode attribute to throw an exception if there is an error.
19
PDO Examples, cont’d // Fetch the database field names. $result = $con->query($query); $row = $result->fetch(PDO::FETCH_ASSOC); PDO::query() executes an SQL statement and returns a result set as a PDOStatement object. PDOStatement::fetch() fetches the next row of the result set. PDO::FETCH_ASSOC returns the row as an associative array indexed by column names.
20
PDO Examples, cont’d // Construct the header row of the HTML table. print " <tr>\n"; foreach ($row as $field => $value) { print " <th>$field</th>\n"; } print " </tr>\n"; Extract the column (field) names of the fetched row to construct the header row of the HTML table.
21
PDO Examples, cont’d // Fetch the matching database table rows. $data = $con->query($query); $data->setFetchMode(PDO::FETCH_ASSOC); // Construct the HTML table row by row. foreach ($data as $row) { print " <tr>\n"; foreach ($row as $name => $value) { print " <td>$value</td>\n"; } print " </tr>\n"; PDOStatement::setFetchMode sets the default fetch mode for this statement.
22
ALTER TABLE Change the structure of an existing table.
Add a new column. Example: Drop a column. ALTER TABLE vendor ADD (vendorphonenumber CHAR(11)); ALTER TABLE vendor DROP (vendorphonenumber); Database Systems by Jukić, Vrbsky, & Nestorov Pearson 2014 ISBN
23
UPDATE Modify data in a table. Examples:
Database Systems by Jukić, Vrbsky, & Nestorov Pearson 2014 ISBN Modify data in a table. Examples: UPDATE product SET productprice = 100 WHERE productid = '4×4'; ALTER TABLE product ADD (discount NUMERIC(3,2)); UPDATE product SET discount = 0.2; Set the value of the discount column in all rows to 0.2.
24
DELETE Delete rows from a table.
Example: Without the WHERE clause, all the table rows will be deleted, resulting in an empty table. DELETE FROM product WHERE productid = '4×4’; Database Systems by Jukić, Vrbsky, & Nestorov Pearson 2014 ISBN
25
PHP query() vs. exec() Use PDO::query() to execute an SQL SELECT statement. Returns a result set as a PDOStatement object. $con = new PDO("mysql:host=localhost;dbname=school", "root", "sesame"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "SELECT * FROM teacher WHERE id = $id"; $data = $con->query($query);
26
PHP query() vs. exec(), cont’d
Use PDO::exec() to execute an SQL INSERT or DELETE statement. Returns the count of affected rows. Teacher Id Last First 7003 Rogers Tom 7008 Thompson Art 7012 Lane John 7051 Flynn Mabel $con = new PDO("mysql:host=localhost;dbname=school", "root", "sesame"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "UPDATE teacher ". "SET first = 'Ronald' " "WHERE first = 'Ron'"; $count = $con->exec($query);
27
Table Join with PHP $first = filter_input(INPUT_GET, "firstName");
$last = filter_input(INPUT_GET, "lastName"); try { $con = new PDO("mysql:host=localhost;dbname=school", "root", "sesame"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "SELECT student.first, student.last, subject ". "FROM student, teacher, class, student_class ". "WHERE teacher.last = '$last' ". "AND teacher.first = '$first' ". "AND teacher_id = teacher.id ". "AND code = class_code ". "AND student.id = student_id ". "ORDER BY subject, student.last"; $data = $con->query($query); $data->setFetchMode(PDO::FETCH_ASSOC);
28
Break
29
SQL Injection Attack A simple query with a teacher id:
$id = filter_input(INPUT_GET, "id"); try { $con = new PDO("mysql:host=localhost;dbname=school", "root", "sesame"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "SELECT * FROM teacher WHERE id = $id"; $data = $con->query($query); $data->setFetchMode(PDO::FETCH_ASSOC); $data contains a result set as a PDOStatement object.
30
SQL Injection Attack, cont’d
Id Last First 7003 Rogers Tom 7008 Thompson Art 7012 Lane John 7051 Flynn Mabel
31
SQL Injection Attack, cont’d
32
Prepared Statement $id = filter_input(INPUT_GET, "id"); try {
$con = new PDO("mysql:host=localhost;dbname=school", "root", "sesame"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "SELECT * FROM teacher WHERE id = :id"; $ps = $con->prepare($query); $ps->execute(array(':id' => $id)); $data = $ps->fetchAll(PDO::FETCH_ASSOC); $data contains an associative array.
33
Prepared Statement, cont’d
34
Prepared Statement, cont’d
Never insert text from a user on the client side directly into an SQL query on the server side. A prepared statement provides some defense against SQL injection attacks. A prepared statement is parsed and compiled once. It can be reused. Performance improvement for queries made from inside PHP loops.
35
Table Join with a Prepared Statement
$con = new PDO("mysql:host=localhost;dbname=school", "root", "sesame"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "SELECT student.first, student.last, subject ". "FROM student, teacher, class, student_class ". "WHERE teacher.last = :last ". "AND teacher.first = :first ". "AND teacher_id = teacher.id ". "AND code = class_code ". "AND student.id = student_id ". "ORDER BY subject, student.last"; $ps = $con->prepare($query); $ps->execute(array(':first' => $first, ':last' => $last)); $data = $ps->fetchAll(PDO::FETCH_ASSOC);
36
Parameter Binding Instead of: Use parameter binding:
$ps->execute(array(':first' => $first, ':last' => $last)); $data = $ps->fetchAll(PDO::FETCH_ASSOC); $ps->bindParam(':first', $first); $ps->bindParam(':last', $last); $ps->execute(); $data = $ps->fetchAll(PDO::FETCH_ASSOC);
37
Views A view allows the structure of a query to be saved in the database. AKA virtual table Not an actual table – no data is saved. Whenever a view is invoked, it executes a query to retrieve data from the actual tables. A view is analogous to a procedure in a programming language. Use a view like any other table.
38
Views, cont’d Which products have more than 3 items sold in all sales transactions? CREATE VIEW products_more_than_3_sold AS SELECT productid, productname, productprice FROM product WHERE productid IN (SELECT productid FROM soldvia GROUP BY productid HAVING SUM(noofitems) > 3);
39
Views, cont’d CREATE VIEW products_more_than_3_sold AS
SELECT productid, productname, productprice FROM product WHERE productid IN (SELECT productid FROM soldvia GROUP BY productid HAVING SUM(noofitems) > 3); SELECT * FROM products_more_than_3_sold; Database Systems by Jukić, Vrbsky, & Nestorov Pearson 2014 ISBN
40
Views, cont’d CREATE VIEW products_in_multiple_trnsc AS SELECT productid, productname, productprice FROM product WHERE productid IN (SELECT productid FROM soldvia GROUP BY productid HAVING COUNT(*) > 1); Database Systems by Jukić, Vrbsky, & Nestorov Pearson 2014 ISBN
41
Views, cont’d Dropping views Example:
SELECT * FROM products_in_multiple_trnsc; Dropping views Example: DROP VIEW products_in_multiple_trnsc; Database Systems by Jukić, Vrbsky, & Nestorov Pearson 2014 ISBN
42
Another Table Creation Example
Database Systems by Jukić, Vrbsky, & Nestorov Pearson 2014 ISBN
43
Another Table Creation Example, cont’d
optional unique Unary relationship Database Systems by Jukić, Vrbsky, & Nestorov Pearson 2014 ISBN
44
Another Table Creation Example, cont’d
CREATE TABLE manager ( managerid CHAR(4) NOT NULL, mfname VARCHAR(15) NOT NULL, mlname VARCHAR(15) NOT NULL, mbdate DATE NOT NULL, msalary NUMERIC(9,2) NOT NULL, mbonus NUMERIC(9,2), mresbuildingid CHAR(3), PRIMARY KEY (managerid) ); CREATE TABLE managerphone ( managerid CHAR(4) NOT NULL, mphone CHAR(11) NOT NULL, PRIMARY KEY (managerid, mphone), FOREIGN KEY (managerid) REFERENCES manager(managerid) Bonuses are optional. Initially optional and not a foreign key. Why?
45
Another Table Creation Example, cont’d
CREATE TABLE building ( buildingid CHAR(3) NOT NULL, bnooffloors INT NOT NULL, bmanagerid CHAR(4) NOT NULL, PRIMARY KEY (buildingid), FOREIGN KEY (bmanagerid) REFERENCES manager(managerid) ); CREATE TABLE inspector ( insid CHAR(3) NOT NULL, insname VARCHAR(15) NOT NULL, PRIMARY KEY (insid)
46
Another Table Creation Example, cont’d
CREATE TABLE inspecting ( insid CHAR(3) NOT NULL, buildingid CHAR(3) NOT NULL, datelast DATE NOT NULL, datenext DATE NOT NULL, PRIMARY KEY (insid, buildingid), FOREIGN KEY (insid) REFERENCES inspector(insid), FOREIGN KEY (buildingid) REFERENCES building(buildingid) ); CREATE TABLE corpclient ( ccid CHAR(4) NOT NULL, ccname VARCHAR(25) NOT NULL, ccindustry VARCHAR(25) NOT NULL, cclocation VARCHAR(25) NOT NULL, ccidreferredby CHAR(4), PRIMARY KEY (ccid), UNIQUE (ccname), FOREIGN KEY (ccidreferredby) REFERENCES corpclient(ccid)
47
Another Table Creation Example, cont’d
CREATE TABLE apartment ( buildingid CHAR(3) NOT NULL, aptno CHAR(5) NOT NULL, anoofbedrooms INT NOT NULL, ccid CHAR(4), PRIMARY KEY (buildingid, aptno), FOREIGN KEY (buildingid) REFERENCES building(buildingid), FOREIGN KEY (ccid) REFERENCES corpclient(ccid) ); CREATE TABLE staffmember ( smemberid CHAR(4) NOT NULL, smembername VARCHAR(15) NOT NULL, PRIMARY KEY (smemberid)
48
Another Table Creation Example, cont’d
CREATE TABLE cleaning ( buildingid CHAR(3) NOT NULL, aptno CHAR(5) NOT NULL, smemberid CHAR(4) NOT NULL, CONSTRAINT cleaningpk PRIMARY KEY (buildingid, aptno, smemberid), CONSTRAINT cleaningfk1 FOREIGN KEY (buildingid, aptno) REFERENCES apartment(buildingid, aptno), CONSTRAINT cleaningfk2 FOREIGN KEY (smemberid) REFERENCES staffmember(smemberid) ); Named constraints
49
Another Table Creation Example, cont’d
INSERT INTO manager VALUES ('M12', 'Boris', 'Grant', '20/Jun/1980', 60000, null, null); ('M23', 'Austin', 'Lee', '30/Oct/1975', 50000, 5000, null); ('M34', 'George', 'Sherman', '11/Jan/1976', 52000, 2000, null); INSERT INTO managerphone VALUES ('M12',' '); INSERT INTO managerphone VALUES ('M12',' '); INSERT INTO managerphone VALUES ('M23',' '); INSERT INTO managerphone VALUES ('M34',' '); INSERT INTO building VALUES ('B1', '5', 'M12'); INSERT INTO building VALUES ('B2', '6', 'M23'); INSERT INTO building VALUES ('B3', '4', 'M23'); INSERT INTO building VALUES ('B4', '4', 'M34');
50
Another Table Creation Example, cont’d
INSERT INTO inspector VALUES ('I11', 'Jane'); INSERT INTO inspector VALUES ('I22', 'Niko'); INSERT INTO inspector VALUES ('I33', 'Mick'); INSERT INTO inspecting VALUES ('I11','B1','15/May/2012','14/May/2013'); INSERT INTO inspecting VALUES ('I11','B2','17/Feb/2013','17/May/2013'); INSERT INTO inspecting VALUES ('I22','B2','17/Feb/2013','17/May/2013'); INSERT INTO inspecting VALUES ('I22','B3','11/Jan/2013','11/Jan/2014'); INSERT INTO inspecting VALUES ('I33','B3','12/Jan/2013','12/Jan/2014'); INSERT INTO inspecting VALUES ('I33','B4','11/Jan/2013','11/Jan/2014'); INSERT INTO corpclient VALUES ('C111', 'BlingNotes', 'Music', 'Chicago', null); ('C222', 'SkyJet', 'Airline', 'Oak Park', 'C111'); ('C777', 'WindyCT', 'Music', 'Chicago', 'C222'); ('C888', 'SouthAlps', 'Sports', 'Rosemont', 'C777');
51
Another Table Creation Example, cont’d
INSERT INTO apartment VALUES ('B1', '21', 1, 'C111'); INSERT INTO apartment VALUES ('B1', '41', 1, null); INSERT INTO apartment VALUES ('B2', '11', 2, 'C222'); INSERT INTO apartment VALUES ('B2', '31', 2, null); INSERT INTO apartment VALUES ('B3', '11', 2, 'C777'); INSERT INTO apartment VALUES ('B4', '11', 2, 'C777'); INSERT INTO staffmember VALUES ('5432', 'Brian'); INSERT INTO staffmember VALUES ('9876', 'Boris'); INSERT INTO staffmember VALUES ('7652', 'Caroline'); INSERT INTO cleaning VALUES ('B1', '21', '5432'); INSERT INTO cleaning VALUES ('B1', '41', '9876'); INSERT INTO cleaning VALUES ('B2', '11', '9876'); INSERT INTO cleaning VALUES ('B2', '31', '5432'); INSERT INTO cleaning VALUES ('B3', '11', '5432'); INSERT INTO cleaning VALUES ('B4', '11', '7652');
52
Constraint Management
ALTER TABLE manager ADD CONSTRAINT fkresidesin FOREIGN KEY (mresbuildingid) REFERENCES building (buildingid); UPDATE manager SET mresbuildingid = 'B1' WHERE managerid = 'M12'; SET mresbuildingid = 'B2' WHERE managerid = 'M23'; SET mresbuildingid = 'B4' WHERE managerid = 'M34'; MODIFY (mresbuildingid NOT NULL);
53
Another Table Creation Example, cont’d
Database Systems by Jukić, Vrbsky, & Nestorov Pearson 2014 ISBN
54
Another Table Creation Example, cont’d
Database Systems by Jukić, Vrbsky, & Nestorov Pearson 2014 ISBN
55
Constraint Management, cont’d
DROP TABLE cleaning; DROP TABLE staffmember; DROP TABLE apartment; DROP TABLE corpclient; DROP TABLE inspecting; DROP TABLE inspector; DROP TABLE managerphone; ALTER TABLE manager DROP CONSTRAINT fkresidesin; DROP TABLE building; DROP TABLE manager;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.