Hello!!
DISCLAIMER: I am self taught. There is a lot of OO programming concepts that I am not familiar with.
I have to build an app using Oracle OCI8 so I decided to create a utility class (my first one!). This class works even though it is very simple:
<?php
/*
* ++Very++ basic Oracle wrapper for PHP inspired by the work of
* Tarmo Protsin <tarmopr@hot.ee> at PHPClasses.org
*
* @author kristo5747
*/
class ociClass {
/**
* Unsure if it matters but I am not using _ in the name of my variables.
*/
var $user;
var $password;
var $database;
var $conn;
var $stmt;
var $res;
var $err;
/**
* Connects to database.
* Returns TRUE if connection succeeded, FALSE otherwise.
* @return boolean
*/
function connect()
{
$this->conn = oci_connect($this->user, $this->password, $this->database);
if (!$this->conn) {
$this->err = oci_error();
echo "Code: " . $this->err["code"] . "\n";
echo "Message: " . $this->err["message"] . "\n";
echo "Position: " . $this->err["offset"] . "\n";
return FALSE;
}
return TRUE;
}
/**
* Executes given query.
* Returns TRUE if query executed successfully, FALSE otherwise.
* @return boolean
*/
function query($sql)
{
$this->stmt = oci_parse($this->conn, $sql);
$this->res = oci_execute($this->stmt);
if (!$this->res) {
$this->err = oci_error($this->stmt);
echo "Code: " . $this->err["code"] . "\n";
echo "Message: " . $this->err["message"] . "\n";
echo "Position: " . $this->err["offset"] . "\n";
return FALSE;
}
return TRUE;
}
function disconnect()
{
oci_close($this->conn);
return TRUE;
}
}
?>
And this is the page I am calling my class from:
<?php
include "ociClass.php";
$orcl = new ociClass();
$orcl->user = "user";
$orcl->password = "password";
$orcl->database = "//Host_Name:Port_Number/SID";
// Check if connection failed.
// If failed (retcode=FALSE) then print out the error and abort script execution.
if (!$orcl->connect())
{
echo "Error: Could not connect to database!\n";
die();
}
$sql = "SELECT TABLE_NAME FROM TABS";
// Check if query failed.
// If failed (retcode=FALSE) then print out the error and abort script execution.
if (!$orcl->query($sql))
{
echo "Error: Could not get data from database!\n";
die();
}
while ($row = oci_fetch_array($orcl->stmt, OCI_ASSOC+OCI_RETURN_NULLS)) {
//Oracle returns all field names in upper case so field names MUST BE in uppercase
// otherwise PHP returns `undefined index` error;
$id = $row['TABLE_NAME'];
echo $id. "\n";
}
$orcl->disconnect();
?>
As you can see, all of it is very basic. How can it be improved? Ideally, I would like to create two additional functions :
B error management [/B]; there is a challenge since oci_connect errors require no handle but oci_execute do. Is overloading the right approach?
B query result management [/B]; instead of naming the fields of the query, I would rather make a method that uses something like an array....
Thanks in advance,
Al.