Home » php, 原创

[原创]以 pear db开发基类创建数据中间层便利对数据库的操作

10 02月 2010 Views: No Comment Tags:

受到pear db_object的启发,觉得是否可以自己创建符合自己项目的基类,通过继承可以快速的实现对说据库相应表的操作方法。 首先定义数据库联接文件conn.inc.php

<?php
/*
 * 用于数据的的联接操作,采用Pear的DB来操纵数据库
 */
  require_once "DB.php";
  $user = 'root';//用户名
  $pass = '';//联连密码
  $host = 'localhost';//服务器名
  $db_name = 'db_name1';//数据库名
  $dsn = "mysql://$user:$pass@$host/$db_name";//
  $B_DB = DB::connect($dsn);//数据库连接操作
 
  if(DB::isError($B_DB)){
  //连接错误处理
    echo "An error occurred while trying to connect to the database server.
\n";
          echo "Error message: " . $B_DB->getMessage() . "
\n";
          echo "A more detailed error description: ";
          die($B_DB->getDebugInfo());
  }
?>

基类文件:BaseClass.php 非完整版本,读者可依自己项目特点抽象出适合的方法;

<?php<br />/*
***********************************************
*        BaseClass.php
*        Base Class of the DB Execute function
*        Version  : 1.0
*        Author   : zhxiyao (zhxiyao#gmail(dot)com)
*        Copyright: www.xixis.net
*        Writed   : 2007/07/20
*        Modified : -
***********************************************
* BaseClass作为数据库操作的基类
* 包含了大多数对数据库操作的方法
* 不要直接实例化本类,要通过继承的方法来使用
* 可以在子类中将个别方法复写以适应特定的表
***********************************************/
include_once("./conn.ini.php");
    class BC_BaseClass{
        var $BV_TableName; //对象表名在继承时负值
 
        var $BV_SelectByID;
        var $DelbyID;
        var $BV_Insert;   //继承时需负值
        var $BV_Update;   //继承时需负值
        var $Error;
 
        /*
            构造函数初始化成员变量
        */
        function __construct(){
                $this->BV_SelectByID = "select * from ".$this->BV_TableName." where ID=?";
                $this->BV_DelbyID = 'delete from '.$this->BV_TableName.' where ID = ?';
        }
 
        /*
            function  BF_SelectByID;
            参数: $ID
            查询ID为$ID的记录
            输出: 查询结果集 为Array
        */
        function BF_SelectByID($ID){
            global $B_DB;
            $array = $B_DB->query($this->BV_SelectByID,$ID);
            if (PEAR::isError($array)) {
                echo "数据库错误: "."\n";
                echo "错误信息: " . $array->getMessage() . "\n";
                echo "详细信息: " . $array->getDebugInfo() . "\n";
            }
 
                $array->fetchInto($row,DB_FETCHMODE_ASSOC);
 
                if (empty($row)) {
                        $this->Error = "没有相关的记录";
                        return;
                }
                return $row;
        }
        /*
            function  BF_SelectBySql;
            参数: $SQL
            查询SQL为$SQL的记录
            输出: 查询结果集 为Array
        */
        function BF_SelectBySql($SQL){
            global $B_DB;
            $result = $B_DB->query($SQL);
            if (DB::isError($result)) {
                $this->Error = $result->getMessage();
                return;
            }
                $rows = array();
            while($result->fetchInto($row,DB_FETCHMODE_ASSOC)){
                $rows[] = $row;
            }
            if (empty($rows)) {
                $this->Error = "无记录.";
                return;
            }
            return $rows;
        }
        /*
            function  BF_Insert;
            参数: $InsertArray
            插入SQL为$Array的记录
            输出: 结果集 为true 或者false
        */
 
        function BF_Insert($InsertArray){
            global $B_DB;
            $array = $B_DB->Prepare($this->BV_Insert);
            $result = $B_DB->execute($array,$InsertArray);
            if (PEAR::isError($result)) {
                echo "数据库错误: " .: "\n";
                echo "错误信息: " . $result->getMessage() . : "\n";
                echo "详细信息: " . $result->getDebugInfo() . "\n";
                return 0;
            }
            else return 1;
        }
        /*
            function  BF_Update;
            参数: $UpdateArray,$ID
            插入对象为$UpdateArray的记录
            输出: 结果集 为true 或者false
        */
        function BF_Update($UpdateArray,$ID){
            global $B_DB;
            $temp=array();
                $temp=$UpdateArray;
                $temp[]=$ID;
 
            $array = $B_DB->Prepare($this->BV_Update);
           $result = $B_DB->execute($array,$temp);
           if (PEAR::isError($result)) {
                echo "数据库错误: " .: "\n";
                echo "错误信息: " . $result->getMessage() . : "\n";
                echo "详细信息: " . $result->getDebugInfo() . "\n";
                return 0;
           }
           else return 1;
        }
        /*
            function  BF_DeleteByID;
            参数: $ID
            插入对象为$Array的记录
            输出: 结果集 为true 或者false
        */
        function BF_DeleteByID($ID){
                global $B_DB;
                $array = $B_DB->prepare($this->BV_DelbyID);
                $result = $B_DB->execute($array,$ID);
                if (DB::isError($result)) {
                        $this->Error = $result->getMessage();
                        echo "数据库错误: " .: "\n";
                	echo "错误信息: " . $result->getMessage() . : "\n";
                	echo "详细信息: " . $result->getDebugInfo() . "\n";
                        return 0;
                }
                else if (!$B_DB->affectedRows()!=0) {
                        $this->Error = '该记录不存在';
                        echo '该记录不存在';
                        return 0;
                }
                else return 1;
    }
    }
 
?>

基类的实例化,加入操作对象是数据库db_name1中的test表:

CREATE TABLE `test` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` int(11) DEFAULT NULL,
  `Bak1` varchar(30) DEFAULT NULL,
  `Bak2` varchar(30) DEFAULT NULL,
  PRIMARY KEY  (`ID`)
) TYPE=MyISAM AUTO_INCREMENT=1 ;

建立包含支持对test表操作的类文件C_Test.php;

<?
/**
 *类名称:BC_Test
 *类方法:
  继承自基类的方法:
 *  BF_SelectByID
 *  BF_SelectBySql
 * BF_Insert
 * BF_Update
 
 * 类开发目标:定义封装数据库中Test表所有操作
 * 作者:zhxiyao
 *
 * @version v1.0 //每修改一次,版本增加小号1.1,大的修改变为2.0
 * 每进行一次修改,一定要在开始说明修改原因,修改后性能的改进
 * @copyright 2007
 */
        include_once("./BaseClass.php");
        class   BC_Test extends BC_BaseClass{
 
                function __construct(){
                        $this->BV_TableName ='test'; //指定操作表名;
                        //初始化表含有的字段;
                        $this->BV_Insert='INSERT INTO `test` (`Name` , `Bak1` , `Bak2`) VALUES (?,?,?)'; 
                        $this->BV_Update='UPDATE `product` SET `Name` = ?,`Bak1` = ?,`Bak2` = ?  WHERE `ID` = ? ';
 
                        parent::__construct();                       
                }
                function 新方法{
 
                }
                function 基类方法名{
                   //复写方法
                }
        }
?>

以此便可快速的实现包含对数据库对应表操作的类。

原创文章如转载,请注明:转载自Xixis Blog [ http://www.xixis.net/ ]
本文链接地址:http://www.xixis.net/archives/change-pear-db-getting-started-guide.html

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.