Presentation is loading. Please wait.

Presentation is loading. Please wait.

CMPE 226 Database Systems September 2 Class Meeting Department of Computer Engineering San Jose State University Fall 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak.

Similar presentations


Presentation on theme: "CMPE 226 Database Systems September 2 Class Meeting Department of Computer Engineering San Jose State University Fall 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak."— Presentation transcript:

1 CMPE 226 Database Systems September 2 Class Meeting Department of Computer Engineering San Jose State University Fall 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak

2 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Some Sources of Data for Visualization  Google “datasets for data visualization”  http://archive.ics.uci.edu/ml/ http://archive.ics.uci.edu/ml/  http://www.kdnuggets.com/datasets/index.html http://www.kdnuggets.com/datasets/index.html  https://www.kaggle.com/competitions https://www.kaggle.com/competitions  http://www.visualizing.org/data/browse http://www.visualizing.org/data/browse  http://datavisualization.ch/datasets/ http://datavisualization.ch/datasets/  http://www.idvbook.com/teaching-aid/data-sets/ http://www.idvbook.com/teaching-aid/data-sets/  http://blog.visual.ly/data-sources/ http://blog.visual.ly/data-sources/  https://www.google.com/publicdata/directory https://www.google.com/publicdata/directory 2

3 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Teams? 3

4 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Relational Databases 4 student name course number course title instructor name room number FrankCMPE101Intro ProgrammingO’Brien432 FrankHIST256European HistoryEvans111 SusanCS153Compiler DesignMak225 EricCS153Compiler DesignMak225 LuisHIST256European HistoryEvans111 LuisCS153Compiler DesignMak225 BillCMPE101Intro ProgrammingO’Brien432 BillHIST256European HistoryEvans111 RosaCS153Compiler DesignMak225 RosaCMPE101Intro ProgrammingO’Brien432 A table of student and course information. 10 rows X 5 columns = 50 data items

5 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Relational Databases, cont’d 5 student name course number FrankCMPE101 FrankHIST256 SusanCS153 EricCS153 LuisHIST256 LuisCS153 BillCMPE101 BillHIST256 RosaCS153 RosaCMPE101 course number course title instructor name room number CMPE101Intro ProgrammingO’Brien432 HIST256European HistoryEvans111 CS153Compiler DesignMak225  Two tables 10 rows X 2 columns = 20 data items 3 rows X 4 columns = 12 data items 32 data items total  Easier to update data. Example: Move CMPE101 to room 400

6 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Keys  A column in one table contains keys to look up rows in another table. 6 student name course number FrankCMPE101 FrankHIST256 SusanCS153 EricCS153 LuisHIST256 LuisCS153 BillCMPE101 BillHIST256 RosaCS153 RosaCMPE101 course number course title instructor name room number CMPE101Intro ProgrammingO’Brien432 HIST256European HistoryEvans111 CS153Compiler DesignMak225

7 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Virtual Tables  Who takes classes from Prof. Mak?  Join operation of the two tables: Combine each row of one table with the corresponding row of the other table based on matching key values 7 student name course number FrankCMPE101 FrankHIST256 SusanCS153 EricCS153 LuisHIST256 LuisCS153 BillCMPE101 BillHIST256 RosaCS153 course number course title instructor name room number CMPE101Intro ProgrammingO’Brien432 HIST256European HistoryEvans111 CS153Compiler DesignMak225

8 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Virtual Tables, cont’d 8 studen t name course number FrankCMPE101 FrankHIST256 SusanCS153 EricCS153 LuisHIST256 LuisCS153 BillCMPE101 BillHIST256 RosaCS153 course number course title instructor name room number CMPE101Intro ProgrammingO’Brien432 HIST256European HistoryEvans111 CS153Compiler DesignMak225 studen t name course number course title instructor name room number FrankCMPE101Intro ProgrammingO’Brien432 FrankHIST256European HistoryEvans111 SusanCS153Compiler DesignMak225 EricCS153Compiler DesignMak225 LuisHIST256European HistoryEvans111 LuisCS153Compiler DesignMak225 BillCMPE101Intro ProgrammingO’Brien432 BillHIST256European HistoryEvans111 RosaCS153Compiler DesignMak225 RosaCMPE101Intro ProgrammingO’Brien432 Join the two tables.

9 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Virtual Tables, cont’d 9 student name instructor name FrankO’Brien FrankEvans SusanMak EricMak LuisEvans LuisMak BillO’Brien BillEvans RosaMak student name course number course title instructor name room number FrankCMPE101Intro ProgrammingO’Brien432 FrankHIST256European HistoryEvans111 SusanCS153Compiler DesignMak225 EricCS153Compiler DesignMak225 LuisHIST256European HistoryEvans111 LuisCS153Compiler DesignMak225 BillCMPE101Intro ProgrammingO’Brien432 BillHIST256European HistoryEvans111 RosaCS153Compiler DesignMak225 RosaCMPE101Intro ProgrammingO’Brien432 The projection operation removes unneeded columns.

10 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Virtual Tables, cont’d  The selection operation chooses only rows with instructor “Mak”.  Project again to remove the unneeded instructor column. 10 student name instructor name SusanMak EricMak LuisMak RosaMak student name Susan Eric Luis Rosa Who takes classes from Prof. Mak?

11 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Relational Algebra  The mathematical theory behind database operations: join project select 11

12 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Client-Server Web Apps 12 Client Side Web Browser Chrome Firefox Safari Microsoft IE Server Side Web Server Apache + PHP HTTP request HTTP response  HTTP request User’s form data  HTTP response Dynamically generated HTML page

13 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Serving Web Pages  The Apache web server serves web pages. Displayed on the client side by web browsers. Web pages can be static or dynamic.  Static web pages:.html HTML files that the web server reads from disk. A static page always displays the same content.  Dynamic web pages:.php Generated by PHP code running on the server. Contains dynamic content. 13

14 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Basic “Naked” HTML  HTML specifies a web page’s Content Structure Semantics  HTML should no longer specify formatting. Separate content from formatting. Formatting tags and attributes are deprecated.  Font, color, alignment, etc.  Formatting should be specified by CSS. Cascading Style Sheets 14

15 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak XAMPP Directory Structure 15 Folder htdocs is the root of all the web pages on your web server.

16 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak HTML Page Template 16 page title body of page

17 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Paragraphs and Headings 17 Chapter 1 Subsection 1.1 Subsection 1.2 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum....

18 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Paragraphs and Headings, cont’d 18... Subsection 1.3 Subsection 1.3.1 Subsection 1.3.2 Subsection 1.3.3 This is a paragraph. Chapter 2 Yet another paragraph.

19 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Paragraphs and Headings, cont’d 19

20 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Ordered and Unordered Lists 20 Unordered list California New York Texas Ordered list CS 146 CS 151 CS 152 CS 153 CS 160 CS 174

21 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Nested Lists 21 Nested list California San Francisco San Jose Los Angeles New York New York City Albany Texas Dallas El Paso

22 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Simple Table 22 Simple table States State Capital Population California Sacramento 38,802,500 New York Albany 19,746,227 Texas Austin 26,956,958

23 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Table with Borders 23 Borders States State Capital Population California Sacramento 38,802,500 New York Albany 19,746,227 Texas Austin 26,956,958

24 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Table with colspan and rowspan 24 Spanning rows and columns States State Capital Population California The Golden State New York Albany Too many! Texas Austin

25 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Links to Pages 25 Links An absolute link to the Paragraphs and Headings page has the complete URL: http://localhost/examples/paragraphs.html A relative link to the Tables page has a URL that is relative to the directory of the current page: tables.html...

26 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Links to Anchor Tags 26... Links to Anchor Tags A link to the the lorem anchor tag on this page uses the location #lorem. Place the anchor tag before the line you want to jump to. You can also jump to the nested anchor tag on the Lists page using the location lists.html#nested Lorem ipsum Lorem ipsum dolor sit amet... Demo

27 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Images 27 An inline image of my two cats. An inline image can serve as a link!

28 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Images, cont’d 28 Demo

29 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Form Data  A user can input data into an HTML form displayed on a client-side web browser.  When the user presses a Submit button, the browser sends to form data to a specified PHP program running on the web server.  The PHP program can use the form data to Query the back-end database. Generate a new HTML page to send to the user’s client-side web browser. 29

30 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Client-Server Web Apps 30 Client Side Web Browser Chrome Firefox Safari Microsoft IE Server Side Web Server Apache + PHP HTTP request HTTP response  HTTP request User’s form data  HTTP response Dynamically generated HTML page

31 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Ways to Send Form Data, cont’d  Get method The form data is appended to the target URL. Good for small amounts of data. The data is visible:  Post method The data is sent via environment variables. Good for larger amounts of data. Slightly more secure than the get method. 31 http://localhost/forms/text.php?firstName=Ron&lastName=Mak

32 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Text Input: HTML Page 32 <form action="text.php" method="get"> User input First name: Last name: forms/text.html

33 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Text Input: PHP Code 33 Text Greeting <?php $first = filter_input(INPUT_GET, "firstName"); print " Hello, $first! \n"; ?> forms/text.php

34 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Checkbox Input: HTML Page 34 <form action="checkbox.php" method="post">... Any formatting? <input type="checkbox" name="strong" value="strong" /> Strong! <input type="checkbox" name="em" value="em" /> Emphasized!... forms/checkbox.html

35 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Checkbox Input: PHP Code 35 <?php $first = filter_input(INPUT_POST, "firstName"); $output = "Hello, $first!"; if (filter_has_var(INPUT_POST, "strong")) { $output = " $output "; } if (filter_has_var(INPUT_POST, "em")) { $output = " $output "; } print $output; ?> forms/checkbox.php

36 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Radio Button Input: HTML Page 36 <form action="radio.php" method="post">... Direction> <input type="radio" name="direction" value="coming" checked /> Coming <input type="radio" name="direction" value="going" /> Going... Every radio button in the same group must have the same name (e.g., direction ). forms/radio.html

37 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Radio Button Input: PHP Code 37 <?php $first = filter_input(INPUT_POST, "firstName"); $direction = filter_input(INPUT_POST, "direction"); if ($direction == "coming") { $output = "Hello"; } else if ($direction == "going") { $output = "Good-bye"; } else { $output = "You are SO confused"; } $output = $output.", $first!";... print $output; ?> forms/radio.php

38 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Select List Input: HTML Page 38 <form action="select.php" method="post">... Language? English Français Deutsch forms/select.html

39 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Select List Input: PHP Code 39 <?php $first = filter_input(INPUT_POST, "firstName"); $direction = filter_input(INPUT_POST, "direction"); $language = filter_input(INPUT_POST, "language"); $error = "You are SO confused"; if ($direction == "coming") { switch ($language) { case "english": $output = "Hello"; break; case "french": $output = "Bonjour"; break; case "german": $output = "Guten tag"; break; default: $output = $error; } } else if ($direction == "going") { switch ($language) { case "english": $output = "Good-bye"; break; case "french": $output = "Au revoir"; break; case "german": $output = "Auf wiedersehen"; break; default: $output = $error; } } else { $output = $error; }... ?> forms/select.php

40 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Break 40

41 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Three-Tier Web Application Architecture 41 Client-side web browser Server-side web server (.html.php images, etc.) Form data Back-end database server (MySQL) Queries Data Dynamically generated web pages

42 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Start the MySQL Database Server 42

43 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak XAMPP Home Page 43 phpMyAdmin is a PHP-based GUI interface to the MySQL database server.

44 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak phpMyAdmin Home Page 44

45 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Database Server Root Password  By default, there is no root password.  Set the root password using phpMyAdmin.  Go to the Users tab.  Edit the root user to change its password. 45

46 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Database Server Root Password, cont’d 46

47 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Enable phpMyAdmin to Connect  phpMyAdmin connects to the MySQL database server as the root user.  Now you must tell phpMyAdmin what the new root password is.  Edit the configuration file XAMPP/xamppfiles/phpmyadmin/config.inc.php Edit the line $cfg['Servers'][$i]['password'] = ' root password '; 47

48 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Add a New Database User  Name the user after yourself or your team. Click “Add user” on the Users tab. Use “localhost” for the host.  Tick the checkbox to create a database with the same name. 48

49 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Create a Table in the New Database 49

50 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Insert Data into the Table 50

51 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Browse the Table Contents 51

52 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak MySQL Command Line Interface 52 ~: /Applications/XAMPP/xamppfiles/bin/mysql -u supercoders -p Enter password: mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | supercoders | +--------------------+ 2 rows in set (0.00 sec) mysql> use supercoders Database changed mysql> show tables; +-----------------------+ | Tables_in_supercoders | +-----------------------+ | people | +-----------------------+ 1 row in set (0.00 sec)

53 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak MySQL Command Line Interface, cont’d 53 mysql> select * from people; +-----+--------+-------+--------+--------+ | id | first | last | gender | salary | +-----+--------+-------+--------+--------+ | 101 | John | Adams | M | 120000 | | 102 | Mary | Smith | F | 155000 | | 105 | Helen | Troy | F | 75000 | | 110 | Albert | Jones | M | 160000 | +-----+--------+-------+--------+--------+ 4 rows in set (0.00 sec) mysql> select * from people -> where first = 'Helen' -> and last = 'Troy'; +-----+-------+------+--------+--------+ | id | first | last | gender | salary | +-----+-------+------+--------+--------+ | 105 | Helen | Troy | F | 75000 | +-----+-------+------+--------+--------+ 1 row in set (0.00 sec) mysql>

54 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Simple End-to-End Web Application!  Client side An HTML form to submit a person’s first and last names.  Server side PHP code that uses the first and last names to query the people table in the back end database. Dynamically generate a new web page containing a table of the query results.  Back end A database table containing people data. 54 Demo

55 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Default Web Page: index.html 55 <form action="queryDB.php" method="get"> User input First name: Last name: people/index.html

56 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP Page: queryDB.php 56 Query Results <?php $first = filter_input(INPUT_GET, "firstName"); $last = filter_input(INPUT_GET, "lastName"); try { // Connect to the database. $con = new PDO("mysql:host=localhost;dbname=supercoders", "supercoders", "sesame"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);... } catch(PDOException $ex) { echo 'ERROR: '.$ex->getMessage(); } ?> PDO documentation: http://php.net/manual/en/book.pdo.php queryDB.php Connect to the database and set $con to refer to the connection object. If an error occurs, throw an exception.

57 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP Page: queryDB.php, cont’d 57 try {... $query = "SELECT * FROM people"; // We're going to construct an HTML table. print " \n"; // Fetch the database field names. $result = $con->query($query); $row = $result->fetch(PDO::FETCH_ASSOC); // Construct the header row of the HTML table. print " \n"; foreach ($row as $field => $value) { print " $field \n"; } print " \n";... } Query the database to get a result set $result. Fetch one $row from the result set as an associative array of field:value elements. Print the $field name. queryDB.php

58 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP Page: queryDB.php, cont’d 58 try {... // Constrain the query if we got first and last names. if ((strlen($first) > 0) && (strlen($last) > 0)) { $query = "SELECT * FROM people ". "WHERE first = '$first' ". "AND last = '$last'"; } // Fetch the matching database table rows. $data = $con->query($query); $data->setFetchMode(PDO::FETCH_ASSOC);... } Query the database again to get the result set $data. queryDB.php

59 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP Page: queryDB.php, cont’d 59 try {... // Construct the HTML table row by row. foreach ($data as $row) { print " \n"; foreach ($row as $name => $value) { print " $value \n"; } print " \n"; } print ” \n";... } Loop over each $row of the result set $data. Loop over the name:value elements of each $row. Print the $value. queryDB.php

60 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Setting the Fetch Mode  Instead of  You can write instead 60 $result = $con->query($query); $row = $result->fetch(PDO::FETCH_ASSOC) $result = $con->query($query); $result->setFetchMode(PDO::FETCH_ASSOC); $row = $result->fetch()

61 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Single-Query Alternative 61 print " \n"; // Query the database. $data = $con->query($query); $data->setFetchMode(PDO::FETCH_ASSOC); // Construct the HTML table row by row. // Start with a header row. $doHeader = true; foreach ($data as $row) {... } print " \n”; queryDB2.php

62 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Single-Query Alternative, cont’d 62 // Construct the HTML table row by row. // Start with a header row. $doHeader = true; foreach ($data as $row) { // The header row before the first data row. if ($doHeader) { print " \n"; foreach ($row as $name => $value) { print " $name \n"; } print " \n"; $doHeader = false; }... } queryDB2.php

63 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Single-Query Alternative, cont’d 63 // Construct the HTML table row by row. // Start with a header row. $doHeader = true; foreach ($data as $row) { // The header row before the first data row.... // Data row. print " \n"; foreach ($row as $name => $value) { print " $value \n"; } print " \n"; } queryDB2.php

64 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Assignment #1  Construct a single MySQL database table that contains some data. Your choice of fields and data values.  Create an HTML page containing various types of input (text, checkboxes, radio buttons, etc.).  Create a PHP page that makes different queries of the database table based on the form data.  Dynamically generate a web page that displays the query results. 64

65 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Assignment #1, cont’d  Make screen shots of your web pages.  Create a “dump” of your database with the mysqldump command located in the XAMPP bin directory: Note: No space between –p and the password. Example: The output file create.sql will allow the graders to recreate your database table. 65 mysqldump –u username –p password dbname > create.sql mysqldump -u supercoders -psesame supercoders > create.sql

66 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Assignment #1, cont’d  Create a zip file named after your team (e.g., supercoders.zip ) containing: Your.html and.php files. Output from the mysqldump command. Screen shots of your web pages.  Email to ron.mak@sjsu.eduron.mak@sjsu.edu Subject line: CMPE 226 Assignment #1 team name CC all team members. 66

67 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Assignment #1, cont’d  This is a team assignment. One submission per team. Each team member receives the same score.  Due Friday, Sept. 11 at 11:59 PM. 67

68 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP Syntax  Very similar to C. 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 68

69 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP Variables  All variable names start with $.  PHP is a dynamically typed language. You don’t declare a variable’s type. A variable can be assigned a value of any type.  PHP data types scalar: integer, float, boolean, string array object resource NULL 69

70 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP Strings  Enclose a string with single or double quotes. Examples:  Variables embedded in a double-quoted string are evaluated: But not: 70 "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.'

71 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP String Operations  The string concatenation operator is.  Some string functions: strlen() strtoupper() strtolower() ucwords() capitalize the first letter of every word 71 Demo $name = $last. ", ". $first; $name.= ", Esq.";

72 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Heredocs  Use a heredoc to avoid string quoting issues. Example: 72 $first = "John"; $last = "Smith"; print <<<HERE First name: $first Last name: $last HERE; Must be on a line by itself with no indentation. Demo

73 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP Constants  Name constants with all uppercase letters, by convention. Constants are not variables, so do not use $.  Examples But not: 73 define (PI, 3.1415926); define (HOST_NAME, "localhost"); print "Host name is ". HOST_NAME; print "Host name is HOST_NAME";

74 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Two Kinds of PHP Arrays  Indexed array Indexes are integers.  Associative array Indexes are strings. key-value pairs, like a hash table. 74

75 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Creating PHP Indexed Arrays  Use the array() function:  Specify the first index value. Subsequent elements are indexed incrementally.  An array of sequential numbers: 75 $bands[] = "Beatles"; $bands[] = "Rolling Stones"; $bands[] = "Queen"; $bands = array("Beatles", "Rolling Stones", "Queen"); $bands = array(2=>"Beatles", "Rolling Stones", "Queen"); $values = range(5, 10);

76 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Creating PHP Associative Arrays  Use the array() function: 76 $states["CA"] = "California"; $states["NY"] = "New York"; $states["TX"] = "Texas"; $states = array( "CA" => "California", "NY" => "New York", "TX" => "Texas" ); An associative array is like a hash table.

77 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Looping over Array Elements  Use the foreach statement: Examples: 77 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

78 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak Multidimensional Arrays 78 $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 ); Demo

79 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP Functions  Syntax for programmer-defined functions: Examples:  A function can optionally return a value. 79 function name ( optional arguments ) { // statements in the body } function doSomething() { … } function sayHello($first, $last) { … } function greet($name, $language = "English") { … } function calculate($input, &$output) { … } return value ; Default value Passed by reference

80 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak 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: 80 global $outsideVar;

81 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PHP Data Objects (PDO)  Create a database abstraction layer: 81 PostgresMySQLOracle PHP Data Objects (PDO) PHP query() PDO documentation: http://php.net/manual/en/book.pdo.php

82 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PDO Examples  Create a new PDO object to represent the database connection.  Set the error mode attribute to throw an exception if there is an error. 82 // Connect to the database. $con = new PDO("mysql:host=localhost;dbname=supercoders", "supercoders", "sesame"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

83 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PDO Examples, cont’d  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. 83 // Fetch the database field names. $result = $con->query($query); $row = $result->fetch(PDO::FETCH_ASSOC);

84 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PDO Examples, cont’d  Extract the column (field) names of the fetched row to construct the header row of the HTML table. 84 // Construct the header row of the HTML table. print " \n"; foreach ($row as $field => $value) { print " $field \n"; } print " \n";

85 Computer Engineering Dept. Fall 2015: September 2 CMPE 226: Database Systems © R. Mak PDO Examples, cont’d  PDOStatement::setFetchMode sets the default fetch mode for this statement. 85 // 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 " \n"; foreach ($row as $name => $value) { print " $value \n"; } print " \n"; }


Download ppt "CMPE 226 Database Systems September 2 Class Meeting Department of Computer Engineering San Jose State University Fall 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak."

Similar presentations


Ads by Google