日期:2013-04-07 浏览次数:20558 次
为了便于自己的开发,但是又不想使用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->connect(DB_DATABASE, DB_HOST, DB_USER_NAME, DB_USER_PASS);
[ 使用方法 ]
//获取所有记录
$sql = "SELECT * FROM table1";
$all_record = $db->get_all($sql);
//获取一条
$sql = "SELECT * FROM table1 WHERE id = '1'";
$one_row = $db->get_one($sql);
//分页查询,提取20条记录
$sql = "SELECT * FROM table1";
$page_record = $db->limit_query($sql, $start=0, $offset=20, $order="ORDER BY id DESC");
//提取指定数目的记录
$sql = "SELECT * FROM table1";
$limit_record = $db->get_limit($sql);
//统计记录数,统计所有类型为学生的
$count = $db->count("table1", "id", "type = 'student'");
//插入一条记录
$info_array = array(
"name" => "heiyeluren",
"type" => "student",
"age" => "22",
"gender" => "boy"
);
$db->insert("table1", $info_array);
//更新一条记录
$info_array = array(
"name" => "heiyeluren",
"type" => "teacher",
"age" => "22",
"gender" => "boy"
);
$db->update("table1", $info_array, "name = 'heiyeluren'");
//删除记录
$db->delete("table1", "name = 'heiyeluren'");
//执行一条无结果集的SQL
$db->execute("DELETE FROM table1 WHERE name = 'heiyeluren'");
[ 类库代码 ]
<?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. */
&nbs