Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 174: Web Programming September 2 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak.

Similar presentations


Presentation on theme: "CS 174: Web Programming September 2 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak."— Presentation transcript:

1 CS 174: Web Programming September 2 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak

2 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Teams 2

3 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Three-Tier Web Application Architecture 3 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

4 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Default Web Page: index.html 4 <form action="queryDB.php" method="get"> User input First name: Last name: For Assignment #1, you should have more than just input text fields in your HTML form!

5 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PHP Page: queryDB.php 5 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.

6 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PHP Page: queryDB.php, cont’d 6 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

7 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PHP Page: queryDB.php, cont’d 7 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

8 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PHP Page: queryDB.php, cont’d 8 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

9 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Setting the Fetch Mode  Instead of  You can write instead 9 $result = $con->query($query); $row = $result->fetch(PDO::FETCH_ASSOC) $result = $con->query($query); $result->setFetchMode(PDO::FETCH_ASSOC); $row = $result->fetch()

10 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Single-Query Alternative 10 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

11 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Single-Query Alternative, cont’d 11 // 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

12 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Single-Query Alternative, cont’d 12 // 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

13 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © 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 13

14 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © 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 14

15 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PHP Strings  Enclose a string with single or double quotes. Examples:  Variables embedded in a double-quoted string are evaluated: But not: 15 "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.'

16 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PHP String Operations  The string concatenation operator is.  Some string functions: strlen() strtoupper() strtolower() ucwords() capitalize the first letter of every word 16 Demo $name = $last. ", ". $first; $name.= ", Esq.";

17 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Heredocs  Use a heredoc to avoid string quoting issues. Example: 17 $first = "John"; $last = "Smith"; print <<<HERE First name: $first Last name: $last HERE; Must be on a line by itself with no indentation. Demo

18 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PHP Constants  Name constants with all uppercase letters, by convention. Constants are not variables, so do not use $.  Examples But not: 18 define (PI, 3.1415926); define (HOST_NAME, "localhost"); print "Host name is ". HOST_NAME; print "Host name is HOST_NAME";

19 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Two Kinds of PHP Arrays  Indexed array Indexes are integers.  Associative array Indexes are strings. key-value pairs, like a hash table. 19

20 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © 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: 20 $bands[] = "Beatles"; $bands[] = "Rolling Stones"; $bands[] = "Queen"; $bands = array("Beatles", "Rolling Stones", "Queen"); $bands = array(2=>"Beatles", "Rolling Stones", "Queen"); $values = range(5, 10);

21 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Creating PHP Associative Arrays  Use the array() function: 21 $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.

22 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Looping over Array Elements  Use the foreach statement: Examples: 22 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

23 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak Multidimensional Arrays 23 $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

24 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PHP Functions  Syntax for programmer-defined functions: Examples:  A function can optionally return a value. 24 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

25 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © 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: 25 global $outsideVar;

26 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PHP Data Objects (PDO)  Create a database abstraction layer: 26 PostgresMySQLOracle PHP Data Objects (PDO) PHP query() PDO documentation: http://php.net/manual/en/book.pdo.php

27 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © 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. 27 // Connect to the database. $con = new PDO("mysql:host=localhost;dbname=supercoders", "supercoders", "sesame"); $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

28 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © 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. 28 // Fetch the database field names. $result = $con->query($query); $row = $result->fetch(PDO::FETCH_ASSOC);

29 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PDO Examples, cont’d  Extract the column (field) names of the fetched row to construct the header row of the HTML table. 29 // Construct the header row of the HTML table. print " \n"; foreach ($row as $field => $value) { print " $field \n"; } print " \n";

30 Computer Science Dept. Spring 2015: February 3 CS 174: Web Programming © R. Mak PDO Examples, cont’d  PDOStatement::setFetchMode sets the default fetch mode for this statement. 30 // 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 "CS 174: Web Programming September 2 Class Meeting Department of Computer Science San Jose State University Fall 2015 Instructor: Ron Mak www.cs.sjsu.edu/~mak."

Similar presentations


Ads by Google