Using Oracle With PHP
Using Oracle With PHP
Choose Topic
Luckily there are other databases out there that help us keep
our data consistent, one of which is Oracle. Since Oracle
supports the use of database transactions "out of the box," it
provides some major enhancements over MySQL.
Getting Oracle
Alternatively, you can buy the CD from the Oracle Store for the
very reasonable price of US$40, which gives you access to the
database as well as some additional tools. This is a great option
for those who don't have blazingly fast Internet access, and it
makes it easier to install the application on additional machines.
next page
Lycos Worldwide Copyright 2004, Lycos, Inc. All Rights Reserved. Lycos is a registered trademark of Carnegie Mellon University.
About Lycos | Help | Feedback | Jobs | Advertise
Your use of this website constitutes acceptance of the Lycos Network Privacy Policy and Terms & Conditions.
Choose Topic
Configuring PHP
I'm sure you've installed PHP many times before, and the
installation just improves with each release, so I'm not going to
give you the blow-by-blow here. Just grab the tarball from the
PHP website or any other mirror, and go through the regular ./
configure options that you use just don't forget to add the
option for Oracle support. Use --with-oci8=[DIR] where DIR is
the directory where you installed Oracle (it will default to your
ORACLE_HOME environment variable, but I used '/usr/local/
oracle/product/8.1.7').
Now that Oracle is installed and configured, you can use the
built-in test database or any other database to which you have
access. But if you want to go any further with this tutorial, you
need to have create, insert, and select privileges on the
database you'll be using.
next page
Lycos Worldwide Copyright 2004, Lycos, Inc. All Rights Reserved. Lycos is a registered trademark of Carnegie Mellon University.
About Lycos | Help | Feedback | Jobs | Advertise
Your use of this website constitutes acceptance of the Lycos Network Privacy Policy and Terms & Conditions.
Choose Topic
phone_tx VARCHAR2(14),
email_tx VARCHAR2(255),
PRIMARY KEY(employee_id_no)
);
If you're familiar with MySQL, you should know all about the
AUTO_INCREMENT attribute, which automatically creates a new id
(each one building, incrementally, on the last) every time a new
record is inserted. In theory, a sequence is the same thing, but
it isn't tied to a particular table. In order to use one effectively,
you must first ask what the next id is, then insert that answer
into the appropriate table. To do this, we tell Oracle to create a
sequence for the employee_id_no field in our employees table,
like so:
Now that we have our basic table, let's take a look at some
specific Oracle functions have at our disposal.
next page
Lycos Worldwide Copyright 2004, Lycos, Inc. All Rights Reserved. Lycos is a registered trademark of Carnegie Mellon University.
About Lycos | Help | Feedback | Jobs | Advertise
Your use of this website constitutes acceptance of the Lycos Network Privacy Policy and Terms & Conditions.
Choose Topic
OCIBindByName()
This is used in conjunction with OCIParse to prepare user-
supplied data as part of our statement.
OCIExecute()
This executes a statement against the database once it is
prepared.
OCIError()
This informs us of any errors that occur with any of our queries.
OCIFetchInto()
This is used in our script to loop through any records that we
retrieve from the database.
OCICommit()
This commits a transaction to the database.
OCIRollback()
This returns the database to a previous state.
Got all that? Once you catch your breath, the next step is to go
ahead and connect to the database.
next page
Lycos Worldwide Copyright 2004, Lycos, Inc. All Rights Reserved. Lycos is a registered trademark of Carnegie Mellon University.
About Lycos | Help | Feedback | Jobs | Advertise
Your use of this website constitutes acceptance of the Lycos Network Privacy Policy and Terms & Conditions.
Choose Topic
order allow,deny
</Files>
<?php
define('DB_USER', 'your-username');
define('DB_PASS', 'your-password');
define('DB_NAME', 'your-database');
?>
<?
require('./db-include.inc');
?>
If you happen to get an error when connecting, and you are certain
that everything your username, password, and database
information is correct, your ORACLE_HOME environment variable may
not be set. Try using this bit of code before the call to OCILogon():
<?php
putenv("ORACLE_HOME=/usr/local/oracle/product/8.1.7");
?>
Now it's time to get down to actually manipulating the data in our
table.
next page
Lycos Worldwide Copyright 2004, Lycos, Inc. All Rights Reserved. Lycos is a registered trademark of Carnegie Mellon University.
About Lycos | Help | Feedback | Jobs | Advertise
Your use of this website constitutes acceptance of the Lycos Network Privacy Policy and Terms & Conditions.
Choose Topic
$strEmail = 'foo@bar.com';
?>
Next, we build our query and substitute the appropriate placeholders for the values
we want to insert. A placeholder is an arbitrary identifier (usually it just matches
the name of the column you are addressing), prefixed by a colon (':') that is placed
in the text of the query string. This is opposed to using the dot ('.') operator to just
concatenate your data into your query string (I'll discuss the benefits of using
OCIBindByName() later).
http://webmonkey.wired.com/webmonkey/01/26/index4a_page6.html?tw=backend (1 of 5)16/11/2004 02:12:30 p.m.
Using Oracle with PHP
<?php
$qsvAddEmployee = "
?>
OK, so I lied: In addition to using placeholders, we also need a few other pieces of
information in the query. Let's take a look at what we're doing here.
We did, in fact, use placeholders which correspond to the column where we will be
inserting the data (i.e., the placeholder ":fname_tx" refers to the column of the
same name). Two things that I have added were the use of "employee_id_no.
nextval" and SYSDATE in the values list. The first actually refers to the sequence we
created earlier, rather than a column in the employees table. The first part of this
statement ("employee_id_no") refers to the sequence name, while the second part
("nextval") tells Oracle to increment the sequence using its INCREMENT_BY value.
Using the keyword SYSDATE tells Oracle that we want to use today's date and time
as the value for both the date the record was created and when it was updated. In
this instance, it isn't necessary to provide placeholders since we won't be supplying
any user-defined data.
After we prepare the query, we call OCIParse() with the connection identifier
established from OCILogon() and the query string we just created. OCIParse() will
return a statement identifier that we will use later on.
<?php
?>
Once we have the statement identifier, we can use it to check for any errors that
came back when attempting to parse the query string. Since OCIError() returns
an associative array, we need to check the "code" element to see if an error code
was returned. If so, we can use OCIRollback() to back out any incremental
changes that were made to the database:
<?php
$arrError = OCIError($iStatement);
if ($arrError['code'])
print $arrError['message'];
OCIRollback($iDBConn);
exit;
?>
In this example, a rollback won't do anything particularly useful, but when you're
updating multiple tables in one script, it can be a lifesaver. Note that even though
we roll back any changes to the database, the sequence will retain its current
incremented value. This ensures that a number in a sequence will never be reused,
as that would be catastrophic to our insert script.
Going back to the example where we build our insert statement using named
placeholders, next we come to the part where we use OCIBindByName() to bind a
specific value to each placeholder. OCIBindByName() requires us to provide it with
a statement identifier from our previous OCIParse() call, the placeholder string to
which we want to bind our variable, the variable we are binding, and the maximum
http://webmonkey.wired.com/webmonkey/01/26/index4a_page6.html?tw=backend (3 of 5)16/11/2004 02:12:30 p.m.
Using Oracle with PHP
size of the field we are addressing. We can see the usage here:
<?php
?>
This provides us with two major benefits. First, it gets rid of the problem of having
to use addslashes() to escape any single quotes in our data, and it also inserts a
NULL into a column rather than the empty string.
Finally, we use OCIExecute() to execute the query after all variables have been
bound. We call it with OCI_DEFAULT as a parameter, which tells Oracle not to auto-
commit the data on success. Again, this doesn't do a whole lot for us in this
example, but would come in handy when updating multiple tables. Once we've
confirmed that the insert was successful, we call OCICommit() to save the changes
to the database.
<?php
@OCIExecute($iStatement, OCI_DEFAULT);
$arrError = OCIError($iStatement);
if ($arrError['code'])
print $arrError['message'];
OCIRollback($iDBConn);
exit;
OCICommit($iDBConn);
?>
OK, now that our new employee information is in the table, how do we get it? In
the next section, we'll go over the use of SELECT statements with Oracle.
next page
Lycos Worldwide Copyright 2004, Lycos, Inc. All Rights Reserved. Lycos is a registered trademark of Carnegie Mellon University.
About Lycos | Help | Feedback | Jobs | Advertise
Your use of this website constitutes acceptance of the Lycos Network Privacy Policy and Terms & Conditions.
Choose Topic
fname_tx,
lname_tx,
phone_tx,
email_tx
FROM employees
fname_tx ASC";
@OCIExecute($iStatement, OCI_DEFAULT);
$arrError = OCIError($iStatement);
if ($arrError['code'])
print $arrError['message'];
exit;
?>
<tr>
<td>ID</td>
<td>FIRST NAME</td>
<td>LAST NAME</td>
<td>EMAIL</td>
<td>PHONE</td>
</tr>
<?
{
http://webmonkey.wired.com/webmonkey/01/26/index4a_page7.html?tw=backend (2 of 3)16/11/2004 02:13:18 p.m.
Using Oracle with PHP
?>
<tr>
</tr>
<? }?>
</table>
Note that this code takes care of all the database interaction and also generates a tabular
display of each record in the employees table just one example of how we can embed HTML
in a PHP script.
That should be enough to get you rolling. But before I set you free to explore on your own, let's
tie up a few loose ends.
next page
Lycos Worldwide Copyright 2004, Lycos, Inc. All Rights Reserved. Lycos is a registered trademark of Carnegie Mellon University.
About Lycos | Help | Feedback | Jobs | Advertise
Your use of this website constitutes acceptance of the Lycos Network Privacy Policy and Terms & Conditions.
Choose Topic
Now that you have your environment all set up and you know
how to insert data into, and select data from, the database, I'm
sure you can see how easy it is to make updates and deletions.
While this code works well for this particular example, you can
extend the functionality to be more general.
To get you started down this path, I suggest you create a class
that corresponds to each of your tables, as well as one that
manages information about your database connection. As you
think of method names for each of your classes, consider things
like createConnection(), insert(), update(), delete(), and
other actions you would perform on a database table.
If you continue to tinker with Oracle and PHP, you'll soon learn
their strengths and weaknesses. And with any luck, you might
Lycos Worldwide Copyright 2004, Lycos, Inc. All Rights Reserved. Lycos is a registered trademark of Carnegie Mellon University.
About Lycos | Help | Feedback | Jobs | Advertise
Your use of this website constitutes acceptance of the Lycos Network Privacy Policy and Terms & Conditions.