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 ● Indexing syntax like Java/C ● E.g. for($i=0;$i<10;$i++) $x[$i] = $i * $i; PHP Arrays ● ● Arrays can be initialised using the fucntion array() with a value list as parameter E.g. $coins = array(1,2,5,10,20,50,100,200); ● A string is an array of characters ● E.g. echo “CP3024”[2] outputs '3' PHP Arrays ● Arrays are collections of name/value pairs ● The following are valid $x[-23] = 44; $uname[“cm1958”] = “Mary”; $uname[“cm1901”] = “Peter”; ● Also known as key/value pairs – “cm1958” is key, “Mary” is value PHP Functions ● PHP functions are declared using syntax function name(arg-list) { Code } ● Value returned using return value; PHP Functions ● Can be recursive ● Declarations can be nested ● Function names can be stored in a variable ● main() is “implicit” function ● Can have default parameters ● Parameters normally “call by value” (like Java and C) PHP Functions ● Example function addup3($x,$y,$z) { ● return $x+$y+$z; } Usage echo addup3(21,22,23); – Outputs 66 Database Access ● Connect to server ● Select database ● Construct SQL query ● Send query to server – Receive “result set” ● Convert result set to array (of strings) ● Repeat as required Database Access ● ● Database connection uses the function mysql_connect(hostname,username, password) ● Returns a PHP “resource”. ● E.g. $dbconn = mysql_connect(“clun.scit.wlv.ac.uk”,”demo”); Database Access ● ● ● MySQL keeps user tables in “areas” called databases. You need to select the relevant database. Use mysql_select_db(dbname) The most recently opened database server connection is used Database Access ● Before querying the database construct the query in SQL and save in a string. $sql="SELECT * FROM gazetteer WHERE feature = ' " . $place ." ' "; ● Extra spaces to make quoting clear ● Double quotes enclose PHP strings. ● In the constructed SQL single quotes enclose the value of $place. Database Access ● ● The function mysql_query() sends the SQL query to the server, a “result set” resource is returned. E.g. $result = mysql_query($sql); ● ● Failure sets $result to “false”, not the same as no matching data found. Use mysql_num_rows($result) to determine rows in result set. Database Access ● ● ● ● The “result set” resource consists of a set of rows of data. mysql_fetch_array(result_set) returns an array of strings, one for each column (field) in the result set. Array element keys are column names as the names appeared in the SQL Repeated calls yield successive rows Global Variables ● PHP has a number of global arrays sometimes called superglobals. The values can be accessed within any function ● $_SERVER – server provided information ● $_GET – values from GET request ● $_POST – values from POST request ● $_ENV – environment information PHP packages ● ● PHP extensions are optional groups of functions that may be included in a PHP build and are part of the interpreter. PHP packages are groups of PHP code included at run time. They are managed by a tool called “pear”. PHP Resources (local) ● Local on-line manual – http://www.scit.wlv.ac.uk/appdocs/php ● Essential reading ● Examples and discussion – ● http://www.scit.wlv.ac.uk/~jphb/sst/php Numerous examples fully described, discussions of image generation, LDAP, security, session control, classes, XML, SOAP and more. ASP ● Micro$soft's Active Server Pages ● Server side scripting similar to PHP ● A variety of scripting languages – ● VBScript (described here) and ASP.NET most popular Always available on IIS servers – Versions available under Apache/Unix ASP/VBscript ● Derived from Visual Basic ● Script enclosed in <% ... %> tags ● May start with – <% @ language = vbscript %> – <% option explicit %> ● ● Means all variables must be declared <% .... code .... %> ASP/VBscript ● ● Language Basics Is object oriented but no user class mechanism. ● ● ● I.e. You can only use “official” objects Variables are typed, conversion routines required Control structures as VB ASP/VBscript ● ● ● Basic example – <table border=6><tr><td bgcolor=black> – <font face = verdana color=green size=3> – <% = time() %> – </font></td></tr></table> Shows time in a box Syntax = function() means display function value on standard output channel ASP/VBscript ● ● ● ● ● Getting values from WWW browser HTTP request is parsed by IIS and results are part of a “request” object. total = cint(request("num1")) + cint(request("num2")) Adds up two numbers associated with names “num1” and “num2” cint() converts strings to integers ASP/VBscript ● ● Output to the page is performed using the write() method of the response class/object. E.g. – ● response.write(“number is “ & num1) & is ASP/VBscript's string concatenation operator Database access ● Accessing a MySQL database ● Create a database connection object ● Execute connect method ● Construct SQL query ● Construct result object ● Execute query method ● Examine result object Database Access ● Basic database connection object set myconn = server.createobject("adodb.connection") ● Before executing connection method need connection specification string connection = "driver={MySQL};server=134.220.4.130;uid =demo;database=mydatabase" ● Connection method myconn.open (connection) Database Access ● Create a “result” object set result = server.createobject("adodb.recordset") ● Construct SQL query sql = "SELECT * FROM gazetteer WHERE feature ='" & request("place") & "'" ● Execute query set result = myconn.execute(sql) Database Access ● ● Unlike PHP, ASP/VBScript does not provide a method to count the rows in a result set Need to loop until “EOF” encountered while not result.EOF .... .... wend JSP ● ● ● Originally Java Server Pages Allows Java code to be used as server side script Either free-standing Java server – ● Tricky to handle anything other than JSP Or via Apache and Tomcat – A separate process that communicates with Apache JSP ● ● ● Apache server forwards requests for JSP to Tomcat process Tomcat process (written in Java) looks for JSP document, converts it to Java code (wrapping HTML in Java output methods), compiles the Java and sends the output back to Apache. Compiled Java is cached for efficiency JSP ● Code is enclosed within <% ... %> – ● ● Inspired by ASP Tomcat provides main() method etc., Tomcat provides a request object with a getParameter() method to retrieve user entered data (as a String) JSP ● Adding up two numbers Stringsn1,sn2; int n1,n2; sn1 = request.getParameter("n1"); sn2 = request.getParameter("n2"); n1 = Integer.parseInt(sn1); n2 = Integer.parseInt(sn2); out.println("<br>The sum is " + (n1+n2)); Database Access ● ● For database access some standard class packages need to be imported. Syntax is similar to Java <%@ page import = "java.io.*" import = "java.lang.*" import = "java.sql.*" %> Database Access ● Before creating any connection objects it is necessary to load the driver class for the specific database server Class.forName("org.gjt.mm.mysql.Driver"); ● This could fail and must be enclosed in a try catch construct Database Access ● ● ● ● Set up a database connection using dbconn = DriverManager.getConnection("jdbc:m ysql://clun.scit.wlv.ac.uk/mydataba se","demo",""); String syntax is specific to the particular driver JDBC = Java Data Base Connector Database Access ● Query is prepared in SQL as a string. ● This is then prepared for processing. String sql = ....... sql = dbconn.prepareStatement(sql); results = sql.executeQuery(); Database Access ● ● There is no way of discovering number of rows in a result set. Scan result set until no more results while(results.next()) { Lat = results.getInt(“Lat”); } Comparison ● PHP ● Advantages – ● Popular, Simple, Extensive Libraries, Free (Open Source), Most platforms, Good debugging, Designed for the purpose Disadvantages – Security niggles, Interpretation overhead Comparison ● ● ● ASP Actually several languages(.NET more recent than VBScript) Advantages – ● Good support, popular, integrates with other products Disadvantages – Single supplier Comparison ● JSP ● Advantages – ● Strength of Java language and standard libraries, security Disadvantages – Complexity, performance, difficult to set up, Comparison ● ● ● C Powerful general purpose close to system language. Advantages – ● Can do anything (almost), performance Disadvantages – Development costs, not specifically designed for WWW backends Comparison ● Perl ● Powerful general purpose ● Advantages – ● Widespread support, lots of quality packages Disadvantages – Obscure syntax Local Resources ● Checkttp://www.scit.wlv.ac.uk/~jphb/sst for a substantial collection of information on server side issues. ● ● Slides prepared by Peter Burden using Open Office version 1.9.79 Background image was taken from a web cam on the Isle of Skye on 21/11/2003 ● http://www.uhi.ac.uk/webcams/index.php?cam=smo&mode=large ● Slides in 44/66 point Verdana and 36 point Courier New Bold ● Notes in 14 point Gill Sans and Courier New Bold