note 40203 added to language.oop
| From: | NJFP at rn2 dot php dot net | Date: | Wed, 25 Feb 2004 05:52:34 +0000 |
| Subject: | note 40203 added to language.oop | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-65688@lists.php.net to get a copy of this message | ||
This is a MYSQL/POSTGRES Database CLASS
<?php
//database type - either mysql or postgres
$dbsystem="mysql";
//database location, name and credentials...
$dbhost="*****";
$dbname="*****";
$dbuser="*****";
$dbpass="*****";
// DB base class defines the minimum operations we need here. You can support
// different dbs by writing a new derived class
class DB
{
var $row;
function DB($sql="")
{
if (strlen($sql))
$this->query($sql);
}
function f($field)
{
return $this->row[$field];
}
//these methods must be overrided by derived classes
function query($sql) { return false; }
function get_insert_id() { return 0; }
function next_record() { return false; }
function get_db_error() {return "";}
}
// MySQL database support
class DB_mysql extends DB
{
var $dblink;
var $dbresult;
function DB_mysql($sql="")
{
$this->dblink=mysql_pconnect(
$GLOBALS["dbhost"],
$GLOBALS["dbuser"],
$GLOBALS["dbpass"])
or die("Unable to connect to database");
mysql_select_db($GLOBALS["dbname"], $this->dblink)
or die("Unable to select database {$GLOBALS[dbname]}");
$this->DB($sql);
}
function query($sql)
{
$this->dbresult=mysql_query($sql, $this->dblink);
if (!$this->dbresult)
{
die("Query failure: ".mysql_error()."<br />$sql");
}
return $this->dbresult;
}
function get_insert_id()
{
return mysql_insert_id($this->dblink);
}
function next_record()
{
$this->row=mysql_fetch_array($this->dbresult);
return $this->row!=FALSE;
}
function get_db_error()
{
return mysql_last_error();
}
}
// Postgres database support
class DB_postgres extends DB
{
var $dblink;
var $dbresult;
function DB_postgres($sql="")
{
$this->dblink=pg_connect(
"host=$GLOBALS[dbhost] ".
"dbname=$GLOBALS[dbname] ".
"user=$GLOBALS[dbuser] ".
"password=$GLOBALS[dbpass]")
or die("Unable to connect to database");
$this->DB($sql);
}
function query($sql)
{
$this->dbresult=pg_exec($sql);
if (!$this->dbresult)
{
die("Query failure: ".$this->get_db_error()."<br />$sql<br
/>");
}
return $this->dbresult;
}
function get_insert_id()
{
$sql = "select currval('pastebin_pid_seq')";
$result = pg_fetch_array($this->query($sql));
return $result[0];
}
function next_record()
{
$this->row=pg_fetch_array($this->dbresult);
return $this->row!=FALSE;
}
function get_db_error()
{
return pg_last_error();
}
}
?>
Call it like:
<?php
$dbclass="DB_".$dbsystem;
$db=new $dbclass;
$db->query("select * from table");
?>
----
Manual Page -- http://www.php.net/manual/en/language.oop.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+40203
Delete -- http://master.php.net/manage/user-notes.php?action=delete+40203&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+40203&report=yes
Search -- http://master.php.net/manage/user-notes.php