---
title: "重新封装的PHPLib DB类（推荐简单项目使用本类库）"
author: "varsoft"
date: "2005-12-26T15:59:00Z"
tags: []
slug: "phplib-db"
draft: false
lastmod: "2005-12-26T15:59:00Z"
id: 873970
url: "https://varsoft.iteye.com/blog/873970"
---

**重新封装的PHPLib DB类** *（推荐简单项目使用本类库）*

为了便于自己的开发，但是又不想使用ADODB、PEAR::DB这样的庞然大物，就在PHPLib DB类的基础上、参考PEAR::DB类，封装了自己的DB类，简单好使，非常方便。目前只针对MySQL有效，没什么技术含量，姑且为参考。

使用本类库只是需要把下面代码保存为database.inc.php或者database.class.php，在自己需要的地方include进来，然后实例化对象，然后调用连接方法，最后在执行操作。

**\[连接数据库 ]**

//包含数据库处理类文件  
include\_once("database.inc.php");

//本地数据库配置  
define("DB\_HOST","localhost");//数据库服务器  
define("DB\_USER\_NAME","root");//数据库用户名  
define("DB\_USER\_PASS","");//密码  
define("DB\_DATABASE","test");//数据库

//连接本地数据库  
$db = new DB\_Sql();  
$db-&gt;connect(DB\_DATABASE, DB\_HOST, DB\_USER\_NAME, DB\_USER\_PASS);

**\[ 使用方法 ]**

//获取所有记录  
$sql = "SELECT * FROM table1";  
$all\_record = $db-&gt;get\_all($sql);

//获取一条  
$sql = "SELECT * FROM table1 WHERE id = '1'";  
$one\_row = $db-&gt;get\_one($sql);

//分页查询，提取20条记录  
$sql = "SELECT * FROM table1";  
$page\_record = $db-&gt;limit\_query($sql, $start=0, $offset=20, $order="ORDER BY id DESC");

//提取指定数目的记录  
$sql = "SELECT * FROM table1";  
$limit\_record = $db-&gt;get\_limit($sql);

//统计记录数，统计所有类型为学生的  
$count = $db-&gt;count("table1", "id", "type = 'student'");

//插入一条记录  
$info\_array = array(  
"name"=&gt; "heiyeluren",  
"type"=&gt; "student",  
"age"=&gt; "22",  
"gender"=&gt; "boy"  
);  
$db-&gt;insert("table1", $info\_array);

//更新一条记录  
$info\_array = array(  
"name"=&gt; "heiyeluren",  
"type"=&gt; "teacher",  
"age"=&gt; "22",  
"gender"=&gt; "boy"  
);  
$db-&gt;update("table1", $info\_array, "name = 'heiyeluren'");

//删除记录  
$db-&gt;delete("table1", "name = 'heiyeluren'");

//执行一条无结果集的SQL  
$db-&gt;execute("DELETE FROM table1 WHERE name = 'heiyeluren'");

**\[ 类库代码 ]**

&lt;?php  
/\**  
\* 文件: database.inc.php  
\* 描述: 数据库操作类  
\* 作者: heiyeluren  
\* 创建: 2005-12-25  
\* 修改: 2005-12-26  
\* 说明: 本库使用PHPLib DB库作为核心, 同时增加一些实用方法, 详细参考注释  
\*/

class DB\_Sql  
{

/* public: connection parameters \*/  
var $Host = "";  
var $Database = "";  
var $User = "";  
var $Password = "";

/* public: configuration parameters \*/  
var $Auto\_Free = 1; ## Set to 1 for automatic mysql\_free\_result()  
var $Debug = 0; ## Set to 1 for debugging messages.  
var $Halt\_On\_Error = "yes"; ## "yes" (halt with message), "no" (ignore errors quietly), "report" (ignore errror, but spit a warning)  
var $PConnect = 0; ## Set to 1 to use persistent database connections  
var $Seq\_Table = "db\_sequence";

/* public: result array and current row number \*/  
var $Record = array();  
var $Row;

/* public: current error number and error text \*/  
var $Errno = 0;  
var $Error = "";

/* public: this is an api revision, not a CVS revision. \*/  
var $type = "mysql";  
//var $revision = "1.2";

/* private: link and query handles \*/  
var $Link\_ID = 0;  
var $Query\_ID = 0;

var $locked = false; ## set to true while we have a lock

/* public: constructor \*/  
function DB\_Sql() {  
$this-&gt;query($query);  
}

/* public: some trivial reporting \*/  
function link\_id() {  
return $this-&gt;Link\_ID;  
}

function query\_id() {  
return $this-&gt;Query\_ID;  
}

/* public: connection management \*/  
function connect($Database = "", $Host = "", $User = "", $Password = "") {  
/* Handle defaults \*/  
if ("" == $Database)  
$Database = $this-&gt;Database;

if ("" == $Host)  
$Host = $this-&gt;Host;

if ("" == $User)  
$User = $this-&gt;User;

if ("" == $Password)  
$Password = $this-&gt;Password;

/* establish connection, select database \*/  
if ( 0 == $this-&gt;Link\_ID ) {

if(!$this-&gt;PConnect) {  
$this-&gt;Link\_ID = mysql\_connect($Host, $User, $Password);  
} else {  
$this-&gt;Link\_ID = mysql\_pconnect($Host, $User, $Password);  
}  
if (!$this-&gt;Link\_ID) {  
$this-&gt;halt("connect($Host, $User, \\$Password) failed.");  
return 0;  
}

if ([!@mysql\_select\_db($Database,$this-&gt;Link\_ID](mailto:!@mysql_select_db%28%24Database,%24this-%3ELink_ID))) {  
$this-&gt;halt("cannot use database ".$Database);  
return 0;  
}  
}

return $this-&gt;Link\_ID;  
}

/* public: discard the query result \*/  
function free() {  
@mysql\_free\_result($this-&gt;Query\_ID);  
$this-&gt;Query\_ID = 0;  
}

/* public: perform a query \*/  
function query($Query\_String) {  
/* No empty queries, please, since PHP4 chokes on them. \*/  
if ($Query\_String == "")  
/* The empty query string is passed on from the constructor,  
\* when calling the class without a query, e.g. in situations  
\* like these: '$db = new DB\_Sql\_Subclass;'  
\*/  
return 0;

if (!$this-&gt;connect()) {  
return 0; /* we already complained in connect() about that. \*/  
};

\# New query, discard previous result.  
if ($this-&gt;Query\_ID) {  
$this-&gt;free();  
}

if ($this-&gt;Debug)  
printf("Debug: query = %s&lt;br&gt;\\n", $Query\_String);

$this-&gt;Query\_ID = @mysql\_query($Query\_String,$this-&gt;Link\_ID);  
$this-&gt;Row = 0;  
$this-&gt;Errno = mysql\_errno();  
$this-&gt;Error = mysql\_error();  
if (!$this-&gt;Query\_ID) {  
$this-&gt;halt("Invalid SQL: ".$Query\_String);  
}

\# Will return nada if it fails. That's fine.  
return $this-&gt;Query\_ID;  
}

/* public: walk result set \*/  
function next\_record() {  
if (!$this-&gt;Query\_ID) {  
$this-&gt;halt("next\_record called with no query pending.");  
return 0;  
}

$this-&gt;Record = @mysql\_fetch\_array($this-&gt;Query\_ID);  
$this-&gt;Row += 1;  
$this-&gt;Errno = mysql\_errno();  
$this-&gt;Error = mysql\_error();

$stat = is\_array($this-&gt;Record);  
if (!$stat && $this-&gt;Auto\_Free) {  
$this-&gt;free();  
}  
return $stat;  
}

/* public: position in result set \*/  
function seek($pos = 0) {  
$status = @mysql\_data\_seek($this-&gt;Query\_ID, $pos);  
if ($status)  
$this-&gt;Row = $pos;  
else {  
$this-&gt;halt("seek($pos) failed: result has ".$this-&gt;num\_rows()." rows.");

/* half assed attempt to save the day,  
\* but do not consider this documented or even  
\* desireable behaviour.  
\*/  
@mysql\_data\_seek($this-&gt;Query\_ID, $this-&gt;num\_rows());  
$this-&gt;Row = $this-&gt;num\_rows();  
return 0;  
}

return 1;  
}

/* public: table locking \*/  
function lock($table, $mode = "write") {  
$query = "lock tables ";  
if(is\_array($table)) {  
while(list($key,$value) = each($table)) {  
// text keys are "read", "read local", "write", "low priority write"  
if(is\_int($key)) $key = $mode;  
if(strpos($value, ",")) {  
$query .= str\_replace(",", " $key, ", $value) . " $key, ";  
} else {  
$query .= "$value $key, ";  
}  
}  
$query = substr($query, 0, -2);  
} elseif(strpos($table, ",")) {  
$query .= str\_replace(",", " $mode, ", $table) . " $mode";  
} else {  
$query .= "$table $mode";  
}  
if(!$this-&gt;query($query)) {  
$this-&gt;halt("lock() failed.");  
return false;  
}  
$this-&gt;locked = true;  
return true;  
}

function unlock() {

// set before unlock to avoid potential loop  
$this-&gt;locked = false;

if(!$this-&gt;query("unlock tables")) {  
$this-&gt;halt("unlock() failed.");  
return false;  
}  
return true;  
}

/* public: evaluate the result (size, width) \*/  
function affected\_rows() {  
return @mysql\_affected\_rows($this-&gt;Link\_ID);  
}

function num\_rows() {  
return @mysql\_num\_rows($this-&gt;Query\_ID);  
}

function num\_fields() {  
return @mysql\_num\_fields($this-&gt;Query\_ID);  
}

/* public: shorthand notation \*/  
function nf() {  
return $this-&gt;num\_rows();  
}

function np() {  
print $this-&gt;num\_rows();  
}

function f($Name) {  
if (isset($this-&gt;Record\[$Name])) {  
return $this-&gt;Record\[$Name];  
}  
}

function p($Name) {  
if (isset($this-&gt;Record\[$Name])) {  
print $this-&gt;Record\[$Name];  
}  
}

/* public: sequence numbers \*/  
function nextid($seq\_name) {  
/* if no current lock, lock sequence table \*/  
if(!$this-&gt;locked) {  
if($this-&gt;lock($this-&gt;Seq\_Table)) {  
$locked = true;  
} else {  
$this-&gt;halt("cannot lock ".$this-&gt;Seq\_Table." - has it been created?");  
return 0;  
}  
}

/* get sequence number and increment \*/  
$q = sprintf("select nextid from %s where seq\_name = '%s'",  
$this-&gt;Seq\_Table,  
$seq\_name);  
if(!$this-&gt;query($q)) {  
$this-&gt;halt('query failed in nextid: '.$q);  
return 0;  
}

/* No current value, make one \*/  
if(!$this-&gt;next\_record()) {  
$currentid = 0;  
$q = sprintf("insert into %s values('%s', %s)",  
$this-&gt;Seq\_Table,  
$seq\_name,  
$currentid);  
if(!$this-&gt;query($q)) {  
$this-&gt;halt('query failed in nextid: '.$q);  
return 0;  
}  
} else {  
$currentid = $this-&gt;f("nextid");  
}  
$nextid = $currentid + 1;  
$q = sprintf("update %s set nextid = '%s' where seq\_name = '%s'",  
$this-&gt;Seq\_Table,  
$nextid,  
$seq\_name);  
if(!$this-&gt;query($q)) {  
$this-&gt;halt('query failed in nextid: '.$q);  
return 0;  
}

/* if nextid() locked the sequence table, unlock it \*/  
if($locked) {  
$this-&gt;unlock();  
}

return $nextid;  
}

/* public: return table metadata \*/  
function metadata($table = "", $full = false) {  
$count = 0;  
$id = 0;  
$res = array();

/*  
\* Due to compatibility problems with Table we changed the behavior  
\* of metadata();  
\* depending on $full, metadata returns the following values:  
\*  
\* - full is false (default):  
\* $result\[]:  
\* \[0]\["table"] table name  
\* \[0]\["name"] field name  
\* \[0]\["type"] field type  
\* \[0]\["len"] field length  
\* \[0]\["flags"] field flags  
\*  
\* - full is true  
\* $result\[]:  
\* \["num\_fields"] number of metadata records  
\* \[0]\["table"] table name  
\* \[0]\["name"] field name  
\* \[0]\["type"] field type  
\* \[0]\["len"] field length  
\* \[0]\["flags"] field flags  
\* \["meta"]\[field name] index of field named "field name"  
\* This last one could be used if you have a field name, but no index.  
\* Test: if (isset($result\['meta']\['myfield'])) { ...  
\*/

// if no $table specified, assume that we are working with a query  
// result  
if ($table) {  
$this-&gt;connect();  
$id = @mysql\_list\_fields($this-&gt;Database, $table);  
if (!$id) {  
$this-&gt;halt("Metadata query failed.");  
return false;  
}  
} else {  
$id = $this-&gt;Query\_ID;  
if (!$id) {  
$this-&gt;halt("No query specified.");  
return false;  
}  
}

$count = @mysql\_num\_fields($id);

// made this IF due to performance (one if is faster than $count if's)  
if (!$full) {  
for ($i=0; $i&lt;$count; $i++) {  
$res\[$i]\["table"] = @mysql\_field\_table ($id, $i);  
$res\[$i]\["name"] = @mysql\_field\_name ($id, $i);  
$res\[$i]\["type"] = @mysql\_field\_type ($id, $i);  
$res\[$i]\["len"] = @mysql\_field\_len ($id, $i);  
$res\[$i]\["flags"] = @mysql\_field\_flags ($id, $i);  
}  
} else { // full  
$res\["num\_fields"]= $count;

for ($i=0; $i&lt;$count; $i++) {  
$res\[$i]\["table"] = @mysql\_field\_table ($id, $i);  
$res\[$i]\["name"] = @mysql\_field\_name ($id, $i);  
$res\[$i]\["type"] = @mysql\_field\_type ($id, $i);  
$res\[$i]\["len"] = @mysql\_field\_len ($id, $i);  
$res\[$i]\["flags"] = @mysql\_field\_flags ($id, $i);  
$res\["meta"]\[$res\[$i]\["name"]] = $i;  
}  
}

// free the result only if we were called on a table  
if ($table) {  
@mysql\_free\_result($id);  
}  
return $res;  
}

/* public: find available table names \*/  
function table\_names() {  
$this-&gt;connect();  
$h = @mysql\_query("show tables", $this-&gt;Link\_ID);  
$i = 0;  
while ($info = @mysql\_fetch\_row($h)) {  
$return\[$i]\["table\_name"] = $info\[0];  
$return\[$i]\["tablespace\_name"] = $this-&gt;Database;  
$return\[$i]\["database"] = $this-&gt;Database;  
$i++;  
}

@mysql\_free\_result($h);  
return $return;  
}

/* private: error handling \*/  
function halt($msg) {  
$this-&gt;Error = @mysql\_error($this-&gt;Link\_ID);  
$this-&gt;Errno = @mysql\_errno($this-&gt;Link\_ID);

if ($this-&gt;locked) {  
$this-&gt;unlock();  
}

if ($this-&gt;Halt\_On\_Error == "no")  
return;

$this-&gt;haltmsg($msg);

if ($this-&gt;Halt\_On\_Error != "report")  
die("Session halted.");  
}

function haltmsg($msg) {  
printf("&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;b&gt;Database error:&lt;/b&gt; %s&lt;br&gt;\\n", $msg);  
printf("&lt;b&gt;MySQL Error&lt;/b&gt;: %s (%s)&lt;br&gt;\\n",  
$this-&gt;Errno,  
$this-&gt;Error);  
}

//----------------------------------  
// 模块: 自定义函数  
// 功能: 部分实用的数据库处理方法  
// 作者: heiyeluren  
// 时间: 2005-12-26  
//----------------------------------

/\**  
\* 方法: execute($sql)  
\* 功能: 执行一条SQL语句，主要针对没有结果集返回的SQL  
\* 参数: $sql需要执行的SQL语句，例如：execute("DELETE FROM table1 WHERE id = '1'")  
\* 返回: 更新成功返回True，失败返回False  
\*/  
function execute($sql)  
{  
if (empty($sql))  
{  
$this-&gt;error("Invalid parameter");  
}  
if (!$this-&gt;query($sql))  
{  
return false;  
}  
return true;  
}

/\**  
\* 方法: get\_all($sql)  
\* 功能: 获取SQL执行的所有记录  
\* 参数: $sql需要执行的SQL,例如: get\_all("SELECT * FROM Table1")  
\* 返回: 返回包含所有查询结果的二维数组  
\*/  
function get\_all($sql)  
{  
$this-&gt;query($sql);  
$result\_array = array();  
while($this-&gt;next\_record())  
{

$result\_array\[] = $this-&gt;Record;  
}  
if (count($result\_array)&lt;=0)  
{  
return 0;  
}  
return $result\_array;  
}

/\**  
\* 方法: get\_one($sql)  
\* 功能: 获取SQL执行的一条记录  
\* 参数: $sql需要执行的SQL,例如: get\_one("SELECT * FROM Table1 WHERE id = '1'")  
\* 返回: 返回包含一条查询结果的一维数组  
\*/  
function get\_one($sql)  
{  
$this-&gt;query($sql);  
if (!$this-&gt;next\_record())  
{  
return 0;  
}  
return $this-&gt;Record;  
}

/\**  
\* 方法: get\_limit($sql, $limit)  
\* 功能: 获取SQL执行的指定数量的记录  
\* 参数:  
\* $sql需要执行的SQL,例如: SELECT * FROM Table1  
\* $limit需要限制的记录数  
\* 例如需要获取10条记录, get\_limit("SELECT * FROM Table1", 10);  
\*  
\* 返回: 返回包含所有查询结果的二维数组  
\*/  
function get\_limit($sql, $limit)  
{  
$this-&gt;query($sql);  
$result\_array = array();  
for ($i=0; $i&lt;$limit&&$this-&gt;next\_record(); $i++)  
{  
$result\_array\[] = $this-&gt;Record;  
}  
if (count($result\_array) &lt;= 0)  
{  
return 0;  
}  
return $result\_array;  
}

/\**  
\* 方法: limit\_query($sql, $start=0, $offset=20, $order="")  
\* 功能: 为分页的获取SQL执行的指定数量的记录  
\* 参数:  
\* $sql需要执行的SQL,例如: SELECT * FROM Table1  
\* $start记录的开始数, 缺省为0  
\* $offset记录的偏移量，缺省为20  
\* $order排序方式，缺省为空，例如：ORDER BY id DESC  
\* 例如需要获取从0到10的记录并且按照ID号倒排, get\_limit("SELECT * FROM Table1", 0, 10, "ORDER BY id DESC");  
\*  
\* 返回: 返回包含所有查询结果的二维数组  
\*/  
function limit\_query($sql, $start=0, $offset=20, $order="")  
{  
$sql = $sql ." $order LIMIT $start,$offset";  
$this-&gt;query($sql);  
$result = array();  
while($this-&gt;next\_record())  
{  
$result\[] = $this-&gt;Record;  
}  
if (count($result) &lt;=0 )  
{  
return 0;  
}  
return $result;  
}

/\**  
\* 方法: count($table,$field="\*", $where="")  
\* 功能: 统计表中数据总数  
\* 参数:  
\* $table需要统计的表名  
\* $field需要统计的字段，默认为*  
\* $where条件语句，缺省为空  
\* 例如按照ID统计所有年龄小于20岁的用户, count("user\_table", "id", "user\_age &lt; 20")  
\*  
\* 返回: 返回统计结果的数字  
\*/  
function count($table,$field="\*", $where="")  
{  
$sql = (empty($where) ? "SELECT COUNT($field) FROM $table" : "SELECT COUNT($field) FROM $table WHERE $where");  
$result = $this-&gt;get\_one($sql);  
if (!is\_array($result))  
{  
return 0;  
}  
return $result\[0];  
}

/\**  
\* 方法: insert($table,$dataArray)  
\* 功能: 插入一条记录到表里  
\* 参数:  
\* $table需要插入的表名  
\* $dataArray需要插入字段和值的数组，键为字段名，值为字段值，例如：array("user\_name"=&gt;"张三", "user\_age"=&gt;"20岁");  
\* 例如比如插入用户张三，年龄为20, insert("users", array("user\_name"=&gt;"张三", "user\_age"=&gt;"20岁"))  
\*  
\* 返回: 插入记录成功返回True，失败返回False  
\*/  
function insert($table,$dataArray)  
{  
if (!is\_array($dataArray) || count($dataArray)&lt;=0)  
{  
$this-&gt;error("Invalid parameter");  
}  
while(list($key,$val) = each($dataArray))  
{  
$field .= "$key,";  
$value .= "'$val',";  
}  
$field = substr($field, 0, -1);  
$value = substr($value, 0, -1);  
$sql = "INSERT INTO $table ($field) VALUES ($value)";  
if (!$this-&gt;query($sql))  
{  
return false;  
}  
return true;  
}

/\**  
\* 方法: update($talbe, $dataArray, $where)  
\* 功能: 更新一条记录  
\* 参数:  
\* $table需要更新的表名  
\* $dataArray需要更新字段和值的数组，键为字段名，值为字段值，例如：array("user\_name"=&gt;"张三", "user\_age"=&gt;"20岁");  
\* $where条件语句  
\* 例如比如更新姓名为张三的用户为李四，年龄为21  
\*update("users", array("user\_name"=&gt;"张三", "user\_age"=&gt;"20岁"), "user\_name='张三'")  
\*  
\* 返回: 更新成功返回True，失败返回False  
\*/  
function update($talbe, $dataArray, $where)  
{  
if (!is\_array($dataArray) || count($dataArray)&lt;=0)  
{  
$this-&gt;error("Invalid parameter");  
}  
while(list($key,$val) = each($dataArray))  
{  
$value .= "$key = '$val',";  
}  
$value = substr($value, 0, -1);  
$sql = "UPDATE $talbe SET $value WHERE $where";  
if (!$this-&gt;query($sql))  
{  
return false;  
}  
return true;  
}

/\**  
\* 方法: delete($table, $where)  
\* 功能: 删除一条记录  
\* 参数:  
\* $table需要删除记录的表名  
\* $where需要删除记录的条件语句  
\* 例如比如要删除用户名为张三的用户，delete("users", "user\_name='张三'")  
\*  
\* 返回: 更新成功返回True，失败返回False  
\*/  
function delete($table, $where)  
{  
if (empty($where))  
{  
$this-&gt;error("Invalid parameter");  
}  
$sql = "DELETE FROM $table WHERE $where";  
if (!$this-&gt;query($sql))  
{  
return false;  
}  
return true;  
}

/\**  
\* 方法: error($msg="")  
\* 功能: 显示错误信息后中止脚本  
\* 参数: $msg需要显示的错误信息  
\* 返回: 无返回  
\*/  
function error($msg="")  
{  
echo "&lt;strong&gt;Error&lt;/strong&gt;: $msg\\n&lt;br&gt;\\n";  
exit();  
}

/\**  
\* 方法：get\_insert\_id()  
\* 功能：获取最后插入的ID  
\* 参数: 无参数  
\* 返回：关闭成功返回ID，失败返回0  
\*/  
function get\_insert\_id()  
{  
return mysql\_insert\_id($this-&gt;Link\_ID);  
}

/\**  
\* 方法：close()  
\* 功能：关闭当前数据库连接  
\* 参数: 无参数  
\* 返回：关闭成功返回true，失败返回false  
\*/  
function close()  
{  
return mysql\_close($this-&gt;Link\_ID);  
}  
}  
?&gt;