This lecture Databases I This covers the (absolute) basics of and how to connect to a database using MDB2. (GF Royle 2006-8, N Spadaccini 2008) I 1 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 2 / 24 What is? tags is a scripting language that is widely used for writing Web pages. It allows the user to write pages that combine static HTML together with embedded code. When such a page is requested by a browser, the page is parsed by the webserver. The static HTML is simply passed straight through to the client, while the code is executed and replaced by its output. The website www.php.net is the primary online reference for. code is incorporated into an HTML document by enclosing it inside special tags.... Here is an example of a fairly minimal snippet of code. <body> print("<h1>db3240z Project</h1>"); </body> (To save space, I am omitting the DOCTYPE line, the <html>...</html> tags and the head-element of the page, but they should be included.) This combined HTML/ document should be saved in a file with a.php extension (such as home.php or test.php etc). (GF Royle 2006-8, N Spadaccini 2008) I 3 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 4 / 24
The is interpreted Testing scripts When the client requests the document, the.php extension tells the Web server to run the file through the interpreter before delivering it to the client. The single statement print "<h1>db3240z Project</h1>"; is executed and produces the output <h1>db3240z Project</h1> This output is then sent to the client along with the static HTML, so all the client sees is the HTML. <body> <h1>db3240z Project</h1></body> If a script contains a syntax error and cannot be parsed by the interpreter, then usually no output at all is generated and nothing is sent to the client. The error messages generated by the interpreter are recorded in the web server s error log: Mon Sep 18 15:00:21 2006] [error] [client 130.95.1.160] Parse error: syntax error, unexpected < in /mnt/data0/cits3240/db3240/public_html/test0.php on line 4 This can make debugging a program a time-consuming and tedious affair edit the webpage, reload in the web browser, then check the error log. (GF Royle 2006-8, N Spadaccini 2008) I 5 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 6 / 24 Standalone To speed up this process, you can run as a standalone program just to debug the portions of the code. While logged in to the server machine, which in our case is db3240.csse.uwa.edu.au simply type php test.php and error messages and/or the output of the script will be produced at the terminal. Of course, once the syntax errors are corrected, you must then ensure that the output is valid HTML. A second example Of course, would not be much use if all it could do was produce static text this example shows how a function can be used. <body> <h1>db3240z Project Page</h1> <p> Today s date is print date("d d F Y"); </p> </body> The date() function returns the current date formatted according to the specified format string: Today s date is Mon 18 September 2006 (GF Royle 2006-8, N Spadaccini 2008) I 7 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 8 / 24
programming Programming As well as an extensive library of built-in functions, is actually a fully-featured (procedural) programming language. A lot of the low-level syntax of is similar to the C programming language, and so is very familiar to C and/or Java programmers. One major different is that in, unlike C and Java, the programmer does not have to declare variables before they are used, and the type system is quite a bit looser. Variables Programming In, variables are represented by a dollar sign ($) followed by the variable name. A variable need not be declared before use, and its type is inferred from the value assigned to it. Thus $a = 10; $name = Australia ; makes $a an integer and $name a string. If you subsequently perform an assignment like $a = $name; then the type of $a is simply reassigned to string. (GF Royle 2006-8, N Spadaccini 2008) I 9 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 10 / 24 Types has 8 basic types: Four scalar types boolean integer float string Two compound types array object Two special types resource NULL Programming Scalar Types Programming The scalar types boolean, integer and float which are used for boolean, integer and floating-point values respectively, behave much as you would expect from experience with their Java counterparts. However strings in are quite different to Java s String. A string behaves as an array of byte-sized characters (hence has no native Unicode support) hence they are mutable. $name = Australia ; $name[0] = B ; print $name; would generate the output Bustralia. (GF Royle 2006-8, N Spadaccini 2008) I 11 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 12 / 24
String Manipulation Programming Which quotes? Programming String manipulation is very important in /MySQL applications because (just as in JDBC) the program must build up the query strings in order to send them to the MySQL server. In Java, the + operator is overloaded to perform string concatenation, but in the corresponding operator is the dot, or period (.). Thus after the code $code = " AUS "; $query = SELECT * FROM Country WHERE Code =. $code; the variable $query would be equal to the string SELECT * FROM Country WHERE Code = AUS Like MySQL, strings in can be created with either single or double quotes. $query = "SELECT * FROM Country WHERE Code = ". $code; The difference between the two types of quote is that if a string is constructed with double quotes, then any variable-name contained within the string is expanded. So a statement like $query = "SELECT * FROM Country WHERE Code = $code"; would substitute the value AUS where the variable $code appears. This makes string construction quite a bit simpler in than in Java. (GF Royle 2006-8, N Spadaccini 2008) I 13 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 14 / 24 Connecting to a database MDB2 There are a variety of different ways to connect to a database in. In particular, supports direct connections to a MySQL database through functions such as mysql_connect(), mysql_query() and so on. These functions work perfectly well, but they are MySQL specific and tie your code to this particular database. A more extensible solution is to route the database commands through a database abstraction layer this provides a database-independent interface combined with different database drivers in much the same way as JDBC. The database abstraction layer that we will use is provided by the MDB2 module from PEAR (the Extension and Application Repository). Information on PEAR in general can be found at http://www.pear.php.net and on MDB2 in particular at http://www.pear.php.net/package/mdb2. The operation of MDB2 is completely analogous to using JDBC the programmer must obtain a connection, then use that connection to execute queries and process the results. (GF Royle 2006-8, N Spadaccini 2008) I 15 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 16 / 24
MDB2 setup Obtaining a connection The first thing that is needed is to ensure that the MDB2 module is loaded in your script. This is accomplished by including the MDB2 code into your script using the require_once statement. require_once "/usr/local/lib/php/mdb2.php"; There are other statements include, require and include_once for including external files that have slightly different behaviour. To obtain a connection you use the function MDB2::connect() where the argument is a data source name. $dsn = "mysqli://db3240:xxxxxx@localhost/db3240"; $conn =& MDB2::connect($dsn) This snippet connects the user db3240 to the database db3240 on the local machine with the password XXXXXX the general syntax of the data source name is phptype://username:password@hostspec/database In our case, the mysqli portion says to use the MySQL Improved driver. (GF Royle 2006-8, N Spadaccini 2008) I 17 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 18 / 24 Reference Assignment The assignment to the variable $conn used the special =& assignment operator which performs a reference assignment. A reference assignment simply makes the variable into a new reference to the same item (array, string, object etc) it does not make a new copy of the underlying item. Reference assignments are familiar to Java programmers because all non-primitive Java assignments are reference assignments. Check the result! The MDB2::connect() function may fail for a number of different reasons (unreachable server, incorrect password etc) and so it is crucial to check that no error has occurred. If an error does occur then the function returns an error object which contains information about the error. if (MDB2::isError($conn)) { print $conn->getuserinfo(); print "\n"; die("connection Failed\n"); This uses the function MDB2::isError() to check if $conn is an error. If it is, then it terminates with some diagnostic information. (GF Royle 2006-8, N Spadaccini 2008) I 19 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 20 / 24
Making a query Making a query involves constructing an SQL statement as a string and then calling the query() method of the $conn object. The syntax for calling an object method in is to use -> where you would use a. in Java. $sql = "SELECT name, population FROM Country WHERE population > 50000000"; $result =& $conn->query($sql); if (MDB2::isError($result)) { die($result->getuserinfo()); This method returns either a result object or an error so once again we make sure to check that the statement executed successfully. Processing the results If there are no errors, then the variable $result refers to an object very similar to a JDBC ResultSet. This result object behaves somewhat like a cursor, in that it has a method fetchrow() that fetches the current row (as an array) and moves down to the next row. while ($row =& $result->fetchrow()) { // do something with the row The fetchrow() method returns NULL if there are no more rows to be fetched, and so incorporating it into a while loop is a simple way to process each row in turn. (GF Royle 2006-8, N Spadaccini 2008) I 21 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 22 / 24 Output Cleanup In this example we will simply print out the data contained in each row, so that the webpage provides information about heavily populated countries. while ($row =& $result->fetchrow()) { print "<p>$row[0] has a population of $row[1]</p>"; Each row is an array containing two elements, which are indexed $row[0] and $row[1] just as in Java, and the print statement prints them out along with suitable HTML tags. Finally the script should release any resources that it currently is holding. $result->free(); $conn->disconnect(); These would happen automatically when the script ends, but if it is a very large script making multiple database connections, then it is better to release them explicitly when they are no longer needed. (GF Royle 2006-8, N Spadaccini 2008) I 23 / 24 (GF Royle 2006-8, N Spadaccini 2008) I 24 / 24