This is an example of a DBI object with PHP. This is a functional object that works well with
MySQL. This can be altered to work with ODBC, Oracle, Postgres...
You will have to change the values of the object properties and fill in the proper username,
password, etc.
<?
/********************************************************
* PHP DBI Object
*
* This object acts like Perls DBI object. To use this
* object just require this object file, and then perform
* the following steps with your statements:
*
* require 'PhpDBI.inc';
* $db = new PhpDBI;
* $sql = "select aField from tableName ";
* $db->connect();
* $db->prepare($sql);
* $db->execute($sql);
* while ($returnVar = mysql_fetch_array($db->sth)) {
* DO_SOMETHING_WITH: $returnVar['aField'];
* }
* $db->disconnect();
********************************************************/
class PhpDBI {
/* DB OBJECT PROPERTIES */
var $dbh = false; // database handler
var $sth; // statement handler (our cursor)
var $user = "USERNAME"; // db username
var $pass = "PASSWORD"; // db password
var $host = "HOSTNAME"; // hostname for database (usually localhost)
var $db = "DATABASE"; // name of database
var $sql; // sql statement
/* METHOD: Connect to Database
* returns: true on a good connection, false otherwise */
function connect() {
$this->dbh = false;
$this->dbh = mysql_connect($this->host,$this->user,$this->pass);
mysql_select_db($this->db,$this->dbh);
if (!$this->dbh)
return false;
else
return $dbh;
}
/* METHOD: Disconnect from database */
function disconnect() {
mysql_close($this->dbh);
$this->dbh = false;
}
/* METHOD: Load SQL statement into object */
function prepare($sql) {
$this->sql = $sql;
}
/* METHOD: Execute a random SQL Query
* expects: SQL String
* boolean $ret ( 1 for needing a return value, 0 for no return) */
function execute($sql) {
if ($this->check())
$this->sth = mysql_query($this->sql,$this->dbh);
}
}