Oracle Consulting Oracle Training Oracle Support Development
Home
Catalog
Oracle Books
SQL Server Books
IT Books
Job Interview Books
eBooks
Rampant Horse Books
911 Series
Pedagogue Books

Oracle Software
image
Write for Rampant
Publish with Rampant
Rampant News
Rampant Authors
Rampant Staff
 Phone
 800-766-1884
Oracle News
Oracle Forum
Oracle Tips
Articles by our Authors
Press Releases
SQL Server Books
image
image

Oracle 11g Books

Oracle tuning

Oracle training

Oracle support

Remote Oracle

STATSPACK Viewer

Privacy Policy

 

   
 

ss

Oracle Tips by Burleson 

Exceptions

PHP5 comes with a predefined class exceptionwhich did not exist in PHP4. What does the class exception look like? Without further ado, here is an excerpt from the PHP5 on-line manual:

Example 19 - 28. The Built in Exception class:

<?php
class Exception
{
 protected $message = 'Unknown exception'; // exception message
 protected $code = 0;                      // user defined exception code
 protected $file;                          // source filename of exception
 protected $line;                          // source line of exception

 function __construct($message = null, $code = 0);

 final function getMessage();             // message of exception
 final function getCode();                // code of exception

 final function getFile();                // source filename
 final function getTrace();               // an array of the backtrace()
 final function getTraceAsString();       // formated string

                                          //of trace

   /* Overrideable */
   function __toString();        // formated string for display
}
?>

So, PHP5 comes with the predefined class exception in which most of the functions cannot be overridden. PHP5, just like Java or C++, knows how to handle exceptions with the so called “try catch blocks”. Before showing how this works, a general introduction is merited.

Exceptionsare a synchronous error handling mechanism used by many modern OO languages. What does the word synchronous mean? Synchronous means that the exception can be thrown at few well defined points and is handled in one well defined point.

In contrast to synchronous events like exceptions, there are asynchronous events like signals, which can be encountered at any time and are not dependent upon anything within the program, but are completely external. A human operator deciding to press <ctrl-C> is an example of an external event, completely independent of anything within the program. Exceptions are just a generalized way of testing an outcome of a certain event by using the if statement. So, what does a try-catch block look like?

        try {
                  .....
                 if ($event) {
                     throw new exception(“Event”,$code);
                 }
                 ..........
                 if ($another_event) {
                     throw new exception(“Event2”, $code2);
                 } /* End of the “try block */ 

        catch (exception $e) {
                if ($e->getcode() == SOMETHING) {
                   do something;
                }
                elseif ($e->getcode() == SOMETHING_ELSE) {
                   do something else;
                }
                else { do something third; }
        } /* End of the catch block */

What is worth noticing here?  The exception being thrown and caught is an object of the predefined class “exception”, which carries an error message, an error code and the source file in which the exception has happened. The class exception can extend to carry more information (objects of the client class are also objects of the class “exception”), but functions that are declared “final” cannot be overridden. 

As this book is a book about both PHP and Oracle, it is worth mentioning that the structure of the “exception” class is ideal for carrying the error code and the error message in a simple exception object.  Below is an example of using exception handling for precisely such a purpose. This example is more complex than those previously considered and is divided into several files which will be reused throughout the book.

The first file is called OCI_Session.php and is shown below:

-- *************************************************
-- Copyright © 2005 by Rampant TechPress
-- This script is free for non-commercial purposes
-- with no warranties.  Use at your own risk.
--
-- To license this script for a commercial purpose,
-- contact info@rampant.cc
-- *************************************************

<?php
        class OCI_Session {
           private $usr;
           private $passw;
           private $tns;
           public $db;
           public $err;
           function __construct($user,$passw,$db)
           {
            if (!defined($db)) {
              $db=$_ENV['TWO_TASK'];
            }  
              $this->usr=$user;
              $this->passw=$passw;
              $this->tns=$db;
          @$this->db=oci_new_connect($user,$passw,$db);
              if (!empty($this->db)) 
                 $this->err=NULL;
              else  {
                 $this->err=OCIError();
              }
           } 

       function __destruct()
           {
              oci_close($this->db);
       } 
           function refresh() {
              @$this->db=oci_new_connect($this->usr,
                                  $this->passw,
                                  $this->tns);
              if (!empty($this->db))
                 $this->err=NULL;
              else  {
                 $this->err=OCIError();
              }
           }
           function commit() {
              OCICommit($this->db);
              $this->err=OCIError($this->db);
           }
           function rollback() {
              OCIRollback($this->db);
              $this->err=OCIError($this->db);
           }

           function getError() {
              return($this->err);
           }
        }
?>

This is a class that defines a connection to an Oracle database.  It contains username, password and database connection string as private members because it is not desirable to change database authorization without control. It contains structure displaying error and some normal functions like commit and rollback. It also contains the function refresh() which will be explained later.

So far, it is noted that the function oci_new_connect()is used to log into an Oracle database. Later, when a few more OCI (OCI = Oracle Call Interface) functions are revealed, more regarding oci_new_connect() can be learned. The next file needed for the example 13 is the file login_form.php, and is shown below:

Example 13 (Cont.)

<?php function login_form($init_usr) { ?>
      <form action=”<?=$_SERVER['PHP_SELF']?>” method="post">
           <center>
             <h2>Database Login</h2>
           </center>
           <hr>
           Username:
           <input type="text" name="user" size="10"
              value= “<?php
                          if (!empty($_POST['user'])) 
                                                            echo
$_POST['user'];
                          else  echo "$init_usr";
                        ?>”       
              maxlength="32"> <BR>
                                 Password:
           <input type="password" name="passwd" size="10" > <BR>
                                 Database:
                                <input type="text" name="database"
size="10" maxsize=32><BR>
           <input type="submit" name="login" value=”Login”>
      </form><br>
      <hr>
<?php } ?>

This is simply a utility function showing the login form. It is created as a function because the form must be “sticky”, not allowing a user to proceed until all the data is right. Using this method, if the database credentials are not right, a call to login_ form() will  return the user back to the login screen.

The next file to look at is example13.php. Now that all the utility parts are represented, example13.php is not too big.  Here it is:

Example 13 (Cont)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html>
<head>
<title>Example 13</title>
</head>
<body>
  <?php
        require_once('OCI_Session.php');
        require('login_form.php');
        if (!isset($_POST['user'])) {
             login_form('SCOTT');
        }
        else {
             try { $dbh=new OCI_Session($_POST['user'],
                                        $_POST['passwd'],
                                        $_POST['database']);
                   if (isset($dbh->err))
                      throw new exception($dbh->err['message']);
                   else
                      echo "<br>Successfully logged in.<br>";
                    }
              catch (exception $e) {
             ?>
     <center>
     <?php
         echo "Exception:".$e->getMessage();
         login_form($_POST['user']);
     ?>
<br>
  </center>
<?php } ?>
</body>
</html>

The logic of this procedure is extremely simple, despite its apparent complexity. If the “user” field is not set, the login form is displayed. Otherwise the script attempts to log into the database using given parameters. If an error flag is set, either an exception is thrown and the login form is redisplayed or a simple text confirmation is written to the screen.

The page generated by the script and reactions to the various types of input are shown on the next page. The pictures will show the initial login form, the form after a successful login and the form after an unsuccessful login attempt. This is the first major HTML form, and it is used in various forms and variations throughout the book. It will be rewritten again and again, using PEAR, ADOdb and OCI8 modules. These modules will be described in detail.

After a successful login, the screen looks like the following:

After an unsuccessful login the error message is written on top of the screen and the user is back at the login form. Screen painting (calling login_form() function) is done from the “catch” block.  This example breaks a few of the rules mentioned earlier, such as the following:

  • It has public data members, accessible from outside. From the pure OO perspective, it is not a correct practice but saves a lot of writing and calling “get” functions just to see an error.

  • It uses echo to output HTML flags on the following line:

 echo "<br>Successfully logged in.<br>";

This was created for aesthetic purposes. In the files comprising example 13, switches between HTML and PHP are made frequently. An additional output of a single line of text does not warrant an additional switch. As indicated earlier, programming rules are not carved in stone and can be broken when there is good reason. The aesthetics of the program certainly belongs to the “good reason” category.

See code depot for complete scripts


The above book excerpt is from:

Easy Oracle PHP

Create Dynamic Web Pages with Oracle Data

ISBN 0-9761573-0-6   

Mladen Gogala

http://www.rampant-books.com/book_2005_2_php_oracle.htm

 

Download your Oracle scripts now:

www.oracle-script.com

The definitive Oracle Script collection for every Oracle professional DBA

Linux Oracle commands syntax poster

ION Oracle tuning software

Oracle data dictionary reference poster



Oracle Forum

BC Oracle consulting support training

BC remote Oracle DBA   

 

   

 Copyright © 1996 -2016 by Burleson. All rights reserved.


Oracle® is the registered trademark of Oracle Corporation. SQL Server® is the registered trademark of Microsoft Corporation. 
Many of the designations used by computer vendors to distinguish their products are claimed as Trademarks
 

Hit Counter