PHP for PL/SQL Developers Lewis Cunningham JP Morgan Chase 1
What is PHP? PHP is a HTML pre-processor PHP allows you to generate HTML dynamically PHP is a scripting language usable on the web, the server and the desktop PHP is embeddable in HTML PHP is resolved on the server, not in the browser PHP has a very easy, and probably familiar, syntax PHP is extremely easy for PL/SQL Developers to add to their toolbox 2
Where did PHP come from? Created by a developer who wanted to make his job easier Was originally just a set of Perl scripts Called Personal Home Page tools Version 2.0 was re-written in C 3.0 extended PHP with many new APIs 4.0 Added bad OOP syntax 5.0 Fixed 4.0 6.0 is on the way 3
How does PHP work? PHP files reside where HTML files live The web server is configured to serve certain extensions as static HTML (ex. HTM) and other extensions as PHP (ex. PHP) HTML is served unchanged, PHP is sent to the PHP processor The PHP processor can talk to databases, perform complex logic and knows how to build HTML PHP returns control to the web server which then returns an HTML page to the requesting browser 4
Why PHP for PL/SQL Devs? Familiar data types, all the usual (sort of) Procedural OR Object syntax Block based Exception handling NULLs Arrays and Objects Large built-in function list 5
Using PHP To use PHP, you'll need to install some softwware Fortunately, PHP runs on pretty much any OS You'll need a web server Download Apache and PHP Download Zend Server CE (I'm using this today) If you are using a database, install the database first - I've had much better luck that way 6
Hello World <html> <body> <?php echo Hello World! ;?> </body> </html> Note: While PHP supports using <% and <? instead of <?php, don t use it. <% is gone in 6 and I hope <? will be gone soon also. 7
Today s quick demo Convert a static HTML form to PHP Have it use an Oracle database Display existing data Add new data Show Oracle s OCI syntax and PHP s PDO syntax In general, if you are working with Oracle, you are better off with OCI 8
User Comments HTML Form A not very useful, static HTML form 9
User Comments HTML Form What does it do? Not much. Can enter first name, last name and some comments. Press Ok and it calls itself, returning as an empty form. What would we like it to do? Enter the same information but save it to a database. Also, display existing comments below the form. 10
User Comments HTML Form name_page.php 11
Same Form, as PHP name_page.php 12
Huh? I just changed the extension from HTML to PHP My web server is configured to recognize the PHP extension and send that request to the PHP processor PHP pre-processes HTML If it finds PHP instructions, it executes them This page has no PHP so the processor passes it through unchanged 13
The First Change PHP Freebie name_page1.php 14
<?php echo $_SERVER['PHP_SELF'] ;?> Remember, <?php tells the preprocessor that PHP code is coming and?> ends it The echo procedure is sort of like HTP.PRN, it sends the text to the web page $ says this is a variable _SESSION is a global super variable Items in [] are array elements, $_SESSION is an associative array PHP instructions end with a ; 15
Starting some real code name_page2.php 16
Line 1 : Start PHP code Lines 3-5 : Initialize variables Line 7 : See if the _POST supervariable has my forms items Lines 8-10 : Assign the values of the _POST array to my variables Line 12 : Display variables to web page Line 14 : End PHP code 17
Changing the HTML name_page2.php 18
Redisplay entered data Remember the echo function sends output to the web page <input type="text" name="first_name" value="<?php echo $fname?>"/> This sets the value attribute of "first_name" to what the user entered We set the values of these variables in the PHP block above User entries will be redisplayed after pressing enter 19
Now when we run, before OK 20
After OK 21
Reusing Code in PHP Include Insert code into another script, will give a warning if the file can't be found Require Insert code into a script, fail with an error if the file can't be loaded Include_once, require_once Same as the above but checks to see if the file has already been loaded and will not load it a second time Files for Include and Require can be anywhere on the file system PHP_INI has an INCLUDE_PATH 22
Best Practice Alert Included and required files Do not put your include files in the document root of your web server You will often put important information, like database passwords, in these files If the files are viewable, someone may find them, even if accidentally You can put these files anywhere, on any file system, that is accessible from a command line 23
Connecting to the Database name_page3.php 24
The connection Yellow is the actual OCI connection string (username, password and database) The code circled in red just displays an error message if the connection fails Htmlentities makes sure the text is safe to display on the web page connect.inc 25
After the connection In this case, unless the connection fails, we don't see any differences View the generated HTML code and there is no difference there either The connection will end when the current page is finished being generated You can use persistent connections and connection pooling (both discussed further, later) 26
Now to see some data At this point we want to see any existing records so we will include code to select and fetch That means creating a table in the database and adding a record user_comments.sql 27
Selecting some data We are adding a select and fetch step at the bottom of our web page name_page4.php 28
Selecting and Fetching oci_fetch.inc 29
Selecting and Fetching Line 3 : This is the select statement. This line is like the parse step in DBMS_SQL Line 5 : Executes the select and checks for success Line 17 : This is the exception code that executes should the oci_execute fail Lines 6 15 : This is where the code is generated An HTML table is created The while loop gets the row data The foreach loops through the columnar data 30
Looping This while loop in this code is a very traditional while. While something is true, continue. The foreach is much like the PL/SQL cursor for loop or looping through an Oracle associative array (which in this case, $row IS an associative array) PHP also offers DO..WHILE traditional do loop which always executes at least once before checking the condition FOR Traditional for loop, for (init, check value, increment) for ($var = 1, $var <= 5, $var++) 31
Selecting and Fetching Oci_fetch_array fetches an easy to use associative array Oci_fetch_array can return an associative array, a numeric array or both Alternatives to oci_fetch_array are Oci_fetch_row like fetch array but with only a numeric index Oci_fetch_all Return ALL rows into a user defined array 32
What it looks like now 33
A little cleanup Best Practice? Time to clean up the HTML a little Moving all executable code to INCLUDE files Personal standard CSS External so that designers own it DB Code External include files so that DB guys own it PHP Code Mostly external so that pure code changes are separate from HTML changes 34
Init.inc init.inc 35
Inserting a record, HTML change name_page5.php 36
Why would insert be at the top? Unless you use AJAX, HTML only does something when the user requests it In this case, the user requests a new page The new page is this page, but with any changes POSTed This is, by default, the only way for HTML to see a change Request Page Make changes Submit Page Server Processes Returns a new page 37
Inserting a record, include file oci_insert.inc 38
Inserting a record Lines 2-6 : Code that was in the HTML file, now moved to the include file Lines 8-10 : oci_parse, the SQL INSERT statement Lines 12-14 : bind the page variables to SQL variables Line 16 : The insert is executed Lines 17-18 : Exception handling if insert fails Line 20 : Success message 39
No what is it doing? 40
Can we improve this? A general best practice for any web application is to not embed your data logic in the application The optimal approach is to make an API available and keep specific knowledge of the database, in the database In this case, both our insert and our select can be moved to a stored procedure Will tackle the insert first 41
A User Comments Package, Spec user_comments_pkg.sql 42
A User Comments Package, Body user_comments_pkg.sql 43
A new oci_insert.inc oci_insert_proc.inc 44
What changed? The only thing that changed is that the insert was converted to a stored proc call The variables are still bound The execution is the same Exception handling is the same The display hasn't changed 45
Bigger changes for the Select oci_select_proc.inc 46
Step by Step We now have 2 cursors A ref cursor is a cursor inside a cursor We get a cursor on the stored proc call and another on the OUT parameter for the return record set We bind the ref parameter (:ref) to the new cursor ($ref_cursor) 47
Step by Step We execute $stmt which is the stored proc call If that is successful, we execute the ref cursor 48
Step by Step The remainder of the code is executed as normal The row fetch is followed by the item fetch, using the $ref_cursor variable instead of the $stmt variable We handle execptions for both executes 49
Using PDO instead of OCI OCI is an oracle specific driver You can't run OCI against MySQL, or other databases PHP offers a native wrapper called PDO With PDO, your code can be reused between databases PDO does not support REF Cursors or some other Oracle specific constructs Oracle recommends using the OCI package 50
References and additional info PHP.net The best resource for any PHP needs PHP.net/Manual Online and downloadable PHP manual Zend.com The Zend engine and plenty of useful documentation eclipse.org/pdt Eclipse PDT project, PHP Development Tools PHPBuiler.com Tutorials, articles, forum 51