44
CP3024 – Lecture 4 CP3024 – Lecture 4 Further server side Further server side scripting scripting

CP3024 – Lecture 4

Embed Size (px)

DESCRIPTION

CP3024 – Lecture 4. Further server side scripting. CP3024 – Lecture 4. PHP Further Features ASP/VB Script JSP (Java) Other techniques. PHP Further Features. Arrays Functions Database access Miscellaneous. PHP Arrays. Arrays do not require declaration Grow automatically - PowerPoint PPT Presentation

Citation preview

Page 1: CP3024 – Lecture 4

CP3024 – Lecture 4CP3024 – Lecture 4

Further server side Further server side scriptingscripting

Page 2: CP3024 – Lecture 4

CP3024 – Lecture 4CP3024 – Lecture 4

● PHP Further FeaturesPHP Further Features● ASP/VB ScriptASP/VB Script● JSP (Java)JSP (Java)● Other techniquesOther techniques

Page 3: CP3024 – Lecture 4

PHP Further FeaturesPHP Further Features● ArraysArrays● FunctionsFunctions● Database accessDatabase access● MiscellaneousMiscellaneous

Page 4: CP3024 – Lecture 4

PHP ArraysPHP Arrays● Arrays do not require declarationArrays do not require declaration● Grow automatically Grow automatically ● Indexing syntax like Java/CIndexing syntax like Java/C● E.g.E.g.

for($i=0;$i<10;$i++) for($i=0;$i<10;$i++) $x[$i] = $i * $i;$x[$i] = $i * $i;

Page 5: CP3024 – Lecture 4

PHP ArraysPHP Arrays● Arrays can be initialised using the fucntion Arrays can be initialised using the fucntion

array() with a value list as parameterarray() with a value list as parameter● E.g.E.g.

$coins = array(1,2,5,10,20,50,100,200);$coins = array(1,2,5,10,20,50,100,200);

● A string is an array of charactersA string is an array of characters● E.g.E.g.

echo “CP3024”[2]echo “CP3024”[2] outputsoutputs '3' '3'

Page 6: CP3024 – Lecture 4

PHP ArraysPHP Arrays● Arrays are collections of name/value pairsArrays are collections of name/value pairs● The following are validThe following are valid

$x[-23] = 44;$x[-23] = 44; $uname[“cm1958”] = “Mary”;$uname[“cm1958”] = “Mary”; $uname[“cm1901”] = “Peter”;$uname[“cm1901”] = “Peter”;

● Also known as key/value pairsAlso known as key/value pairs– ““cm1958” is key, “Mary” is valuecm1958” is key, “Mary” is value

Page 7: CP3024 – Lecture 4

PHP FunctionsPHP Functions● PHP functions are declared using syntaxPHP functions are declared using syntax

  functionfunction name(arg-list)name(arg-list)

  {{

  CodeCode

  }}● Value returned usingValue returned using

returnreturn valuevalue;;

Page 8: CP3024 – Lecture 4

PHP FunctionsPHP Functions● Can be recursiveCan be recursive● Declarations can be nestedDeclarations can be nested● Function names can be stored in a Function names can be stored in a

variablevariable● main() is “implicit” functionmain() is “implicit” function● Can have default parametersCan have default parameters● Parameters normally “call by value” (like Parameters normally “call by value” (like

Java and C)Java and C)

Page 9: CP3024 – Lecture 4

PHP FunctionsPHP Functions● ExampleExample

function addup3($x,$y,$z)function addup3($x,$y,$z)

{{ return $x+$y+$z; }return $x+$y+$z; }● UsageUsage

echo addup3(21,22,23);echo addup3(21,22,23);– Outputs 66Outputs 66

Page 10: CP3024 – Lecture 4

Database AccessDatabase Access● Connect to serverConnect to server● Select databaseSelect database● Construct SQL queryConstruct SQL query● Send query to serverSend query to server

– Receive “result set”Receive “result set”● Convert result set to array (of strings)Convert result set to array (of strings)● Repeat as requiredRepeat as required

Page 11: CP3024 – Lecture 4

Database AccessDatabase Access● Database connection uses the functionDatabase connection uses the function● mysql_connect(mysql_connect(hostname,username, hostname,username,

passwordpassword))● Returns a PHP “resource”.Returns a PHP “resource”.● E.g.E.g.

$dbconn = $dbconn = mysql_connect(“clun.scit.wlv.ac.uk”,”demo”);mysql_connect(“clun.scit.wlv.ac.uk”,”demo”);

Page 12: CP3024 – Lecture 4

Database AccessDatabase Access● MySQL keeps user tables in “areas” called MySQL keeps user tables in “areas” called

databases. You need to select the databases. You need to select the relevant database.relevant database.

● Use Use mysql_select_db(mysql_select_db(dbnamedbname))● The most recently opened database The most recently opened database

server connection is usedserver connection is used

Page 13: CP3024 – Lecture 4

Database AccessDatabase Access● Before querying the database construct Before querying the database construct

the query in SQL and save in a string.the query in SQL and save in a string. $sql=$sql=""SELECT * FROM gazetteer WHERE SELECT * FROM gazetteer WHERE

feature = feature = ' "' " . $place . . $place ." ' "" ' ";;● Extra spaces to make quoting clearExtra spaces to make quoting clear● Double quotes enclose PHP strings.Double quotes enclose PHP strings.● In the constructed SQL single quotes In the constructed SQL single quotes

enclose the value of enclose the value of $place$place..

Page 14: CP3024 – Lecture 4

Database AccessDatabase Access● The function The function mysql_query()mysql_query() sends the SQL sends the SQL

query to the server, a “result set” query to the server, a “result set” resource is returned.resource is returned.

● E.g.E.g. $result = mysql_query($sql);$result = mysql_query($sql);

● Failure sets Failure sets $result$result to “false”, not the to “false”, not the same as no matching data found.same as no matching data found.

● Use Use mysql_num_rows($result)mysql_num_rows($result) to to determine rows in result set.determine rows in result set.

Page 15: CP3024 – Lecture 4

Database AccessDatabase Access● The “result set” resource consists of a set The “result set” resource consists of a set

of rows of data.of rows of data.● mysql_fetch_array(mysql_fetch_array(result_setresult_set)) returns an returns an

array of strings, one for each column array of strings, one for each column (field) in the result set.(field) in the result set.

● Array element keys are column names as Array element keys are column names as the names appeared in the SQLthe names appeared in the SQL

● Repeated calls yield successive rowsRepeated calls yield successive rows

Page 16: CP3024 – Lecture 4

Global VariablesGlobal Variables● PHP has a number of global arrays PHP has a number of global arrays

sometimes called superglobals. The sometimes called superglobals. The values can be accessed within any values can be accessed within any functionfunction

● $_SERVER$_SERVER – server provided information – server provided information● $_GET$_GET – values from GET request – values from GET request● $_POST$_POST – values from POST request – values from POST request● $_ENV$_ENV – environment information – environment information

Page 17: CP3024 – Lecture 4

PHP packagesPHP packages● PHP extensions are optional groups of PHP extensions are optional groups of

functions that may be included in a PHP functions that may be included in a PHP build and are part of the interpreter.build and are part of the interpreter.

● PHP packages are groups of PHP code PHP packages are groups of PHP code included at run time. They are managed included at run time. They are managed by a tool called “by a tool called “pearpear”. ”.

Page 18: CP3024 – Lecture 4

PHP Resources PHP Resources (local)(local)

● Local on-line manualLocal on-line manual– http://www.scit.wlv.ac.uk/appdocs/phphttp://www.scit.wlv.ac.uk/appdocs/php

● Essential readingEssential reading● Examples and discussionExamples and discussion

– http://www.scit.wlv.ac.uk/~jphb/sst/phphttp://www.scit.wlv.ac.uk/~jphb/sst/php● Numerous examples fully described, Numerous examples fully described,

discussions of image generation, LDAP, discussions of image generation, LDAP, security, session control, classes, XML, security, session control, classes, XML, SOAP and more.SOAP and more.

Page 19: CP3024 – Lecture 4

ASPASP● Micro$soft's Active Server PagesMicro$soft's Active Server Pages● Server side scripting similar to PHPServer side scripting similar to PHP● A variety of scripting languagesA variety of scripting languages

– VBScript (described here) and ASP.NET most VBScript (described here) and ASP.NET most popularpopular

● Always available on IIS serversAlways available on IIS servers– Versions available under Apache/UnixVersions available under Apache/Unix

Page 20: CP3024 – Lecture 4

ASP/VBscriptASP/VBscript● Derived from Visual BasicDerived from Visual Basic● Script enclosed in Script enclosed in <%<% ... ... %>%> tags tags● May start withMay start with

– <% @ language = vbscript %><% @ language = vbscript %>– <% option explicit %><% option explicit %>

● Means all variables must be declaredMeans all variables must be declared

● <%<% .... code .... .... code .... %>%>

Page 21: CP3024 – Lecture 4

ASP/VBscriptASP/VBscript● Language BasicsLanguage Basics● Is object oriented but no user class Is object oriented but no user class

mechanism.mechanism.● I.e. You can only use “official” objectsI.e. You can only use “official” objects

● Variables are typed, conversion routines Variables are typed, conversion routines requiredrequired

● Control structures as VBControl structures as VB

Page 22: CP3024 – Lecture 4

ASP/VBscriptASP/VBscript● Basic example Basic example

– <table border=6><tr><td bgcolor=black><table border=6><tr><td bgcolor=black>– <font face = verdana color=green size=3><font face = verdana color=green size=3>– <% = time() %><% = time() %>– </font></td></tr></table></font></td></tr></table>

● Shows time in a boxShows time in a box● Syntax Syntax = function()= function() means display means display

function value on standard output function value on standard output channelchannel

Page 23: CP3024 – Lecture 4

ASP/VBscriptASP/VBscript● Getting values from WWW browserGetting values from WWW browser● HTTP request is parsed by IIS and results HTTP request is parsed by IIS and results

are part of a “request” object.are part of a “request” object.● total = cint(request("num1")) + total = cint(request("num1")) +

cint(request("num2"))cint(request("num2"))● Adds up two numbers associated with Adds up two numbers associated with

names “names “num1num1” and “” and “num2num2””● cint()cint() converts strings to integers converts strings to integers

Page 24: CP3024 – Lecture 4

ASP/VBscriptASP/VBscript● Output to the page is performed using the Output to the page is performed using the write()write() method of the method of the responseresponse class/object.class/object.

● E.g.E.g.– response.write(“number is “ & num1)response.write(“number is “ & num1)

● & is ASP/VBscript's string concatenation & is ASP/VBscript's string concatenation operatoroperator

Page 25: CP3024 – Lecture 4

Database accessDatabase access● Accessing a MySQL databaseAccessing a MySQL database● Create a database connection objectCreate a database connection object● Execute connect methodExecute connect method● Construct SQL queryConstruct SQL query● Construct result objectConstruct result object● Execute query methodExecute query method● Examine result objectExamine result object

Page 26: CP3024 – Lecture 4

Database AccessDatabase Access● Basic database connection objectBasic database connection object

set myconn = set myconn = server.createobject("adodb.connection")server.createobject("adodb.connection")

● Before executing connection method need Before executing connection method need connection specification stringconnection specification string connection = connection = "driver={MySQL};server=134.220.4.130;ui"driver={MySQL};server=134.220.4.130;uid=demo;database=mydatabase"d=demo;database=mydatabase"

● Connection methodConnection method myconn.open (connection)myconn.open (connection)

Page 27: CP3024 – Lecture 4

Database AccessDatabase Access● Create a “result” objectCreate a “result” object

set result = set result = server.createobject("adodb.recordset")server.createobject("adodb.recordset")

● Construct SQL queryConstruct SQL query sql = "SELECT * FROM gazetteer WHERE sql = "SELECT * FROM gazetteer WHERE feature ='" & request("place") & "'"feature ='" & request("place") & "'"

● Execute queryExecute query set result = myconn.execute(sql)set result = myconn.execute(sql)

Page 28: CP3024 – Lecture 4

Database AccessDatabase Access● Unlike PHP, ASP/VBScript does not Unlike PHP, ASP/VBScript does not

provide a method to count the rows in a provide a method to count the rows in a result setresult set

● Need to loop until “EOF” encounteredNeed to loop until “EOF” encountered while not result.EOFwhile not result.EOF ........ ........ wendwend

Page 29: CP3024 – Lecture 4

JSPJSP● Originally Java Server Pages Originally Java Server Pages ● Allows Java code to be used as server Allows Java code to be used as server

side scriptside script● Either free-standing Java serverEither free-standing Java server

– Tricky to handle anything other than JSPTricky to handle anything other than JSP● Or via Apache and TomcatOr via Apache and Tomcat

– A separate process that communicates with A separate process that communicates with ApacheApache

Page 30: CP3024 – Lecture 4

JSPJSP● Apache server forwards requests for JSP Apache server forwards requests for JSP

to Tomcat processto Tomcat process● Tomcat process (written in Java) looks for Tomcat process (written in Java) looks for

JSP document, converts it to Java code JSP document, converts it to Java code (wrapping HTML in Java output methods), (wrapping HTML in Java output methods), compiles the Java and sends the output compiles the Java and sends the output back to Apache.back to Apache.

● Compiled Java is cached for efficiencyCompiled Java is cached for efficiency

Page 31: CP3024 – Lecture 4

JSPJSP● Code is enclosed within Code is enclosed within <%<% ... ... %>%>

– Inspired by ASPInspired by ASP● Tomcat provides Tomcat provides main()main() method etc., method etc.,● Tomcat provides a request object with a Tomcat provides a request object with a getParameter()getParameter() method to retrieve user method to retrieve user entered data (as a entered data (as a StringString))

Page 32: CP3024 – Lecture 4

JSPJSP● Adding up two numbersAdding up two numbers

StringString sn1,sn2;sn1,sn2; int n1,n2;int n1,n2; sn1 = request.getParameter("n1");sn1 = request.getParameter("n1"); sn2 = request.getParameter("n2");sn2 = request.getParameter("n2"); n1 = Integer.parseInt(sn1);n1 = Integer.parseInt(sn1); n2 = Integer.parseInt(sn2);n2 = Integer.parseInt(sn2); out.println("<br>The sum is " + out.println("<br>The sum is " + (n1+n2));(n1+n2));

Page 33: CP3024 – Lecture 4

Database AccessDatabase Access● For database access some standard class For database access some standard class

packages need to be imported.packages need to be imported.● Syntax is similar to JavaSyntax is similar to Java

<%@ page <%@ page import = "java.io.*"import = "java.io.*" import = "java.lang.*"import = "java.lang.*" import = "java.sql.*"import = "java.sql.*" %>%>

Page 34: CP3024 – Lecture 4

Database AccessDatabase Access● Before creating any connection objects it Before creating any connection objects it

is necessary to load the driver class for is necessary to load the driver class for the specific database serverthe specific database server

Class.forName("org.gjt.mm.mysql.Driver");Class.forName("org.gjt.mm.mysql.Driver");

● This could fail and must be enclosed in a This could fail and must be enclosed in a try catchtry catch construct construct

Page 35: CP3024 – Lecture 4

Database AccessDatabase Access● Set up a database connection usingSet up a database connection using● dbconn = dbconn = DriverManager.getConnection("jdbc:mDriverManager.getConnection("jdbc:mysql://clun.scit.wlv.ac.uk/mydatabaysql://clun.scit.wlv.ac.uk/mydatabase","demo","");se","demo","");

● String syntax is specific to the particular String syntax is specific to the particular driverdriver

● JDBC = Java Data Base ConnectorJDBC = Java Data Base Connector

Page 36: CP3024 – Lecture 4

Database AccessDatabase Access● Query is prepared in SQL as a string.Query is prepared in SQL as a string.● This is then prepared for processing.This is then prepared for processing.

String sql = .......String sql = ....... sql = dbconn.prepareStatement(sql);sql = dbconn.prepareStatement(sql); results = sql.executeQuery();results = sql.executeQuery();

Page 37: CP3024 – Lecture 4

Database AccessDatabase Access● There is no way of discovering number of There is no way of discovering number of

rows in a result set.rows in a result set.● Scan result set until no more resultsScan result set until no more results

while(results.next())while(results.next()) {{ Lat = results.getInt(“Lat”);Lat = results.getInt(“Lat”); }}

Page 38: CP3024 – Lecture 4

ComparisonComparison● PHPPHP● AdvantagesAdvantages

– Popular, Simple, Extensive Libraries, Free Popular, Simple, Extensive Libraries, Free (Open Source), Most platforms, Good (Open Source), Most platforms, Good debugging, Designed for the purposedebugging, Designed for the purpose

● DisadvantagesDisadvantages– Security niggles, Interpretation overheadSecurity niggles, Interpretation overhead

Page 39: CP3024 – Lecture 4

ComparisonComparison● ASPASP● Actually several languages(.NET more Actually several languages(.NET more

recent than VBScript)recent than VBScript)● AdvantagesAdvantages

– Good support, popular, integrates with other Good support, popular, integrates with other productsproducts

● DisadvantagesDisadvantages– Single supplier Single supplier

Page 40: CP3024 – Lecture 4

ComparisonComparison● JSPJSP● AdvantagesAdvantages

– Strength of Java language and standard Strength of Java language and standard libraries, securitylibraries, security

● DisadvantagesDisadvantages– Complexity, performance, difficult to set up,Complexity, performance, difficult to set up,

Page 41: CP3024 – Lecture 4

ComparisonComparison● CC● Powerful general purpose close to system Powerful general purpose close to system

language.language.● AdvantagesAdvantages

– Can do anything (almost), performanceCan do anything (almost), performance● DisadvantagesDisadvantages

– Development costs, not specifically designed Development costs, not specifically designed for WWW backendsfor WWW backends

Page 42: CP3024 – Lecture 4

ComparisonComparison● PerlPerl● Powerful general purposePowerful general purpose● AdvantagesAdvantages

– Widespread support, lots of quality packagesWidespread support, lots of quality packages● DisadvantagesDisadvantages

– Obscure syntaxObscure syntax

Page 43: CP3024 – Lecture 4

Local ResourcesLocal Resources● CheckCheck ttp://www.scit.wlv.ac.uk/~jphb/sst ttp://www.scit.wlv.ac.uk/~jphb/sst

for a substantial collection of information for a substantial collection of information on server side issues.on server side issues.

Page 44: CP3024 – Lecture 4

● Slides prepared by Peter Burden using Slides prepared by Peter Burden using Open Office version 1.9.79Open Office version 1.9.79

● Background image was taken from a web Background image was taken from a web cam on the Isle of Skye on 21/11/2003cam on the Isle of Skye on 21/11/2003

● http://www.uhi.ac.uk/webcams/index.php?cam=smo&mode=largehttp://www.uhi.ac.uk/webcams/index.php?cam=smo&mode=large

● Slides in 44/66 point Verdana and 36 point Courier New BoldSlides in 44/66 point Verdana and 36 point Courier New Bold

● Notes in 14 point Gill Sans and Courier New BoldNotes in 14 point Gill Sans and Courier New Bold