PHP introduction University of California, Berkeley School of Information IS 257: Database Management IS 257 – Fall 2014 2014.10.14 SLIDE 1 Lecture Outline • Review – Databases for Web Applications – Overview • ColdFusion – DiveShop in ColdFusion • PHP – DiveShop in PHP • More on MySQL and SQL IS 257 – Fall 2014 2014.10.14 SLIDE 2 Lecture Outline • Review – Databases for Web Applications – Overview • ColdFusion – DiveShop in ColdFusion • PHP – DiveShop in PHP • More on MySQL and SQL IS 257 – Fall 2014 2014.10.14 SLIDE 3 Dynamic Web Applications 2 Web Server Internet Files CGI DBMS Server database database database Clients IS 257 – Fall 2014 2014.10.14 SLIDE 4 Server Interfaces SQL HTML DHTML Web Server JavaScript Native DB Interfaces Database Web DB CGI App ODBC Web Server API’s ColdFusion Native DB interfaces JDBC PhP Perl Web Application Server Adapted from John P Ashenfelter, Choosing a Database for Your Web Site IS 257 – Fall 2014 Java ASP 2014.10.14 SLIDE 5 Web Application Server Software • • • • • • ColdFusion PHP ASP JSP Django All of the are server-side scripting languages that embed code in HTML pages IS 257 – Fall 2014 2014.10.14 SLIDE 6 Lecture Outline • Review – Databases for Web Applications – Overview • ColdFusion • PHP – DiveShop in PHP • Introduction to ORACLE and SQL-Plus IS 257 – Fall 2014 2014.10.14 SLIDE 7 Web Application Server Software • • • • • • ColdFusion PHP ASP JSP Django All of the are server-side scripting languages that embed code in HTML pages IS 257 – Fall 2014 2014.10.14 SLIDE 8 Coldfusion • Coldfusion was one of the first server-side scripting languages and it is still available and used – Originally produced by a company called Allaire, it is now owned by Adobe and is in version 11 – It has always been a commercial product since the mid-1990’s IS 257 – Fall 2014 2014.10.14 SLIDE 9 ColdFusion • Developing WWW sites typically involved a lot of programming to build dynamic sites – e.g. Pages generated as a result of catalog searches, etc. • ColdFusion was designed to permit the construction of dynamic web sites with only minor extensions to HTML through a DBMS interface IS 257 – Fall 2014 2014.10.14 SLIDE 10 ColdFusion • Started as CGI – Drawback, as previously discussed, is that the entire system is run for each cgi invocation • Split into cooperating components – Windows service -- runs constantly – Server modules for 4 main Web Server API (glue that binds web server to ColdFusion service) {Apache, ISAPI, NSAPI, WSAPI} – Special CGI scripts for other servers IS 257 – Fall 2014 2014.10.14 SLIDE 11 What ColdFusion is Good for • Putting up databases onto the Web • Handling dynamic databases (Frequent updates, etc) • Making databases searchable and updateable by users • The basic scripting elements are simple, and similar in style to other server-side scripting languages (but the syntax is often different) IS 257 – Fall 2014 2014.10.14 SLIDE 12 Coldfusion • The Coldfusion engine runs in parallel with the web server, and is passed any page in the web server directories that has the appropriate file name extension (.cfm) • The engine processes any Coldfusion script on the web page and passes back an HTML page with the scripts replaced by the script result • As a simple example… IS 257 – Fall 2014 2014.10.14 SLIDE 13 Coldfusion Templates • Assume we have a database named contents_of_my_shopping_cart.mdb -- single table called contents... – With attributes “Item”, “Date_of_item”, “Price” • Create an HTML page (uses extension .cfm), before <HEAD>... • <CFQUERY NAME= ”cart" DATASOURCE=“contents_of_my_shopping_ca rt"> SELECT * FROM contents ; </CFQUERY> IS 257 – Fall 2014 2014.10.14 SLIDE 14 Coldfusion Templates cont. • • • • • • • • • • • • • <HTML>… the cfquery goes here… <HEAD> <TITLE>Contents of My Shopping Cart</TITLE> </HEAD> <BODY> <H1>Contents of My Shopping Cart</H1> <CFOUTPUT QUERY= ”cart"> <B>#Item#</B> <BR> #Date_of_item# <BR> $#Price# <P> </CFOUTPUT> </BODY> </HTML> IS 257 – Fall 2014 2014.10.14 SLIDE 15 Templates cont. Contents of My Shopping Cart Bouncy Ball with Psychedelic Markings 12 December 1998 $0.25 Shiny Blue Widget 14 December 1998 $2.53 Large Orange Widget 14 December 1998 $3.75 IS 257 – Fall 2014 2014.10.14 SLIDE 16 CFIF and CFELSE <CFOUTPUT QUERY= ”cart"> Item: #Item# <BR> <CFIF #Picture# EQ""> <IMG SRC=“generic_picture.jpg"> <BR> <CFELSE> <IMG SRC="#Picture#"> <BR> </CFIF> </CFOUTPUT> IS 257 – Fall 2014 2014.10.14 SLIDE 17 More Templates <CFQUERY DATASOURCE = “AZ2”> INSERT INTO Employees(firstname, lastname, phoneext) VALUES(‘#firstname#’, ‘#lastname#’, ‘#phoneext#’) </CFQUERY> <HTML><HEAD><TITLE>Employee Added</TITLE> <BODY><H1>Employee Added</H1> <CFOUTPUT> Employee <B>#firstname# #lastname#</B> added. </CFOUTPUT></BODY> </HTML> IS 257 – Fall 2014 2014.10.14 SLIDE 18 CFML ColdFusion Markup Language • Read data from and update data to databases and tables • Create dynamic data-driven pages • Perform conditional processing • Populate forms with live data • Process form submissions • Generate and retrieve email messages • Perform HTTP and FTP function • Perform credit card verification and authorization • Read and write client-side cookies IS 257 – Fall 2014 2014.10.14 SLIDE 19 Requirements • Unix or Windows systems • Install as SuperUser • Databases must be defined via “data source names (DSNs) by administrator IS 257 – Fall 2014 2014.10.14 SLIDE 20 Requirements and Set Up • Field names should be devoid of spaces. Use the underscore character, like new_items instead of "new items." • Use key fields. Greatly reduces search time. • Check permissions on the individual tables in your database and make sure that they have read-access for the username your Web server uses to log in. • If your fields include large blocks of text, you'll want to include basic HTML coding within the text itself, including boldface, italics, and paragraph markers. IS 257 – Fall 2014 2014.10.14 SLIDE 21 Lecture Outline • Review – Databases for Web Applications – Overview • ColdFusion • PHP – DiveShop in PHP • More on ORACLE and SQL-Plus IS 257 – Fall 2014 2014.10.14 SLIDE 22 PHP • PHP is an Open Source Software project with many programmers working on the code. – Commonly paired with MySQL, another OSS project – Free – Both Windows and Unix support • Estimated that more than 250,000 web sites use PHP as an Apache Module. IS 257 – Fall 2014 2014.10.14 SLIDE 23 PHP Syntax • Similar to “C” or Java (note lines end with “;”) <HTML><BODY> <?php $myvar = “Hello World”; echo $myvar ; ?> </BODY></HTML> • Includes most programming structures (Loops, functions, Arrays, etc.) • Loads HTML form variables so that they are addressable by name IS 257 – Fall 2014 2014.10.14 SLIDE 24 Combined with MySQL • DBMS interface appears as a set of functions: <HTML><BODY> <?php mysql_connect(“localhost”, “usename”, “password”); mysql_select_db(“mydb”); $result = mysql_query(“SELECT * FROM employees”); while ($r = mysql_fetch_array($result,MYSQL_ASSOC)) { printf("<center><H2>%s",$r[”LAST_NAME"]); printf(”, %s</H2></center> ",$r[”FIRST_NAME"]); } ?></BODY></HTML> IS 257 – Fall 2014 2014.10.14 SLIDE 25 Making the PW External • Problem: the database and PW are in the source… <HTML><BODY> <?php mysql_connect(“localhost”, “usename”, “password”); mysql_select_db(“mydb”); $result = mysql_query(“SELECT * FROM employees”); while ($r = mysql_fetch_array($result,MYSQL_ASSOC)) { printf("<center><H2>%s",$r[”LAST_NAME"]); printf(”, %s</H2></center> ",$r[”FIRST_NAME"]); } ?></BODY></HTML> IS 257 – Fall 2014 2014.10.14 SLIDE 26 Making the PW External <HTML><BODY> <?php include 'msqlini.php'; mysql_connect($host,$user,$pw) or die("Could not connect: " . mysql_error()); mysql_select_db(“mydb”); $result = mysql_query(“SELECT * FROM employees”); while ($r = mysql_fetch_array($result,MYSQL_ASSOC)) { printf("<center><H2>%s",$r[”LAST_NAME"]); printf(”, %s</H2></center> ",$r[”FIRST_NAME"]); } ?></BODY></HTML> IS 257 – Fall 2014 2014.10.14 SLIDE 27 Making the PW External msqlini.php <?php $inifile = "/home/ray/.mysql_settings_harbinger.ini"; /* Access required data for database access from isolated file */ if (!$settings = parse_ini_file($inifile, TRUE)) throw new exception('Unable to open ' . $file . '.'); $host = $settings['database']['host']; $dbname = $settings['database']['dbname']; $user = $settings['database']['username']; $pw = $settings['database']['password']; ?> IS 257 – Fall 2014 2014.10.14 SLIDE 28 Making the PW External • .mysql_settings_harbinger.ini [database] driver = mysql host = localhost dbname = ray username = ray password = whatever_your_pw_is port=3306 IS 257 – Fall 2014 2014.10.14 SLIDE 29 More protection… • For data input and passing parameters you will also need to use parameterized or “prepared” SQL statements to avoid the possibility of SQL Injection attacks: IS 257 – Fall 2014 2014.10.14 SLIDE 30 Mysqli – an enhanced interface include 'msqlini.php’; $mysqli = new mysqli($host,$user,$pw,$dbname); if ($mysqli->connect_error) { echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_ $cust_id = $_GET["cust_id"]; $cust_id = mysql_real_escape_string($cust_id); /* start first prepared statement */ $stmt = $mysqli->stmt_init(); if ($stmt->prepare("SELECT * FROM DIVECUST where Customer_No= ? ")) { if (!$stmt->bind_param("i", $cid)) { echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error; } $cid = $cust_id; if (!$stmt->execute()) { echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; } $stmt->bind_result($custid,$name,$street,$city,$state,$zip,$country,$phone, $contact); IS 257 – Fall 2014 2014.10.14 SLIDE 31 Diveshop PHP • Examples on Harbinger… • Example source on class web site IS 257 – Fall 2014 2014.10.14 SLIDE 32 ASP – Active Server Pages • Another server-side scripting language • From Microsoft using Visual Basic as the Language model (VBScript), though Javascript (actually MS Jscript) is also supported • Works with Microsoft IIS and gives access to ODBC databases • Most commonly used for Access or MS SQL Server IS 257 – Fall 2014 2014.10.14 SLIDE 33 ASP Syntax <% SQL="SELECT last, first FROM employees ORDER BY last" set conn = server.createobject("ADODB.Connection") conn.open “employee" set people=conn.execute(SQL) %> <% do while not people.eof set resultline=people(0) & “, “ & people(1) & “<BR>” Response.Write(resultline) people.movenext loop%> <% people.close %> IS 257 – Fall 2014 2014.10.14 SLIDE 34 Lecture Outline • Review – Databases for Web Applications – Overview • ColdFusion – DiveShop in ColdFusion • PHP – DiveShop in PHP • More on MySQL and SQL IS 257 – Fall 2014 2014.10.14 SLIDE 35 Today • More on SQL for data manipulation and modification IS 257 – Fall 2014 2014.10.14 SLIDE 36 SELECT • Syntax: – SELECT [DISTINCT] attr1, attr2,…, attr3 as label, function(xxx), calculation, attr5, attr6 FROM relname1 r1, relname2 r2,… rel3 r3 WHERE condition1 {AND | OR} condition2 ORDER BY attr1 [DESC], attr3 [DESC] IS 257 – Fall 2014 2014.10.14 SLIDE 37 SELECT Conditions • • • • • • • • • • = equal to a particular value >= greater than or equal to a particular value > greater than a particular value <= less than or equal to a particular value <> or != not equal to a particular value LIKE ‘%wom_n%’ (Note different wild card from Access) opt1 SOUNDS LIKE opt2 IN (‘opt1’, ‘opt2’,…,’optn’) BETWEEN opt1 AND opt2 IS NULL or IS NOT NULL IS 257 – Fall 2014 2014.10.14 SLIDE 38 Aggregate (group by) Functions • • • • • • • • • COUNT(dataitem) COUNT(DISTINCT expr) AVG(numbercolumn) SUM(numbercolumn) MAX(numbercolumn) MIN(numbercolumn) STDDEV(numbercolumn) VARIANCE(numbercolumn) and other variants of these… IS 257 – Fall 2014 2014.10.14 SLIDE 39 Numeric Functions • • • • • • • • • ABS(n) ACOS(n) ASIN(n) ATAN(n) ATAN2(n, m) CEIL(n) COS(n) COSH(n) CONV(n, fbase,t-base) • COT(n) IS 257 – Fall 2014 • • • • • • • • • DEGREES(n) EXP(n) EXP(n) FLOOR(n) LN(n) LOG(n,b) MOD(n) PI() POWER(n,p) • • • • • • • • ROUND(n) SIGN(n) SIN(n) SINH(n) SQRT(n) TAN(n) TANH(n) TRUNCATE( n,m) 2014.10.14 SLIDE 40 Character Functions returning character values • • • • CHAR(n,…) CONCAT(str1,str2,…) LOWER(char) LPAD(char, n,char2), RPAD(char, n,char2) • LTRIM(char, n, cset), RTRIM(char, n, cset) IS 257 – Fall 2014 • REPLACE(char, srch, repl) • SOUNDEX(char) • SUBSTR(char, m, n) • UPPER(char) 2014.10.14 SLIDE 41 Character Function returning numeric values • • • • • • • ASCII(char) INSTR(char1, char2) LENGTH(char) BIT_LENGTH(str) CHAR_LENGTH(str) LOCATE(substr,str) LOCATE(substr,str,po s) • and many other variants. IS 257 – Fall 2014 2014.10.14 SLIDE 42 Date functions • ADDDATE(dt, INTERVAL expr unit) or ADDDATE(dt, days) • ADDTIME(dttm, time) • LAST_DAY(dt) • MONTH(dt) – YEAR(dt) – DAY(dt) • MONTHNAME(dt) • NOW() • NEW_TIME(d, z1, z2) -- PST, AST, etc. • NEXT_DAY(d, dayname) • STR_TO_DATE(str,format) • SYSDATE() IS 257 – Fall 2014 2014.10.14 SLIDE 43 Assignment 3 • Assignment 3 is some additional (and occasionally more complex) searches to be run on the Diveshop database • These should be run via the command line (via login to ischool.berkeley.edu) • Assignment 3 is posted on the class web site • Walkthrough online version • Due Thursday, Oct. 24th IS 257 – Fall 2014 2014.10.14 SLIDE 44