喜悦国际村 
» 游客:  注册 | 登录 | 搜索 | 统计 | 喜悦证交所 | 帮助

RSS 订阅当前论坛  

[北京]代朋友公司招聘PHP高级程序员多名

上一主题 下一主题
 54  1/6  1  2  3  4  5  6  > 
     
标题: 给一个朋友的db类!(经过我扩展功能的)  
 
Double_ycn (Double_ycn)
金牌会员
Rank: 6Rank: 6
版主



UID 18281
精华 6
积分 1618
帖子 1498
金钱 1558 喜悦币
威望 60
人脉 0
阅读权限 70
注册 2003-2-8
状态 离线
给一个朋友的db类!(经过我扩展功能的)

先把类都贴出来.然后介绍怎么使用...


db类:db_mysql.php

<?php

class mysql {

    var 
$Host;
    var 
$Database;
    var 
$User;
    var 
$Password;

    var 
$table;                                            //数据表
    
var $errMes        =array();                            //记录错误信息
    
var $field        =array();                            //查询字段

    
function mysql($host$dbuser$dbpass$db)
    {
        
$this->Host $host//主机 
        
$this->User $dbuser//用户
        
$this->Password $dbpass//密码
        
$this->Database $db//数据库名       
    


    var 
$Auto_Free 0## 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 $Seq_Table "db_sequence";

    var 
$Record = array();
    var 
$Row;

    var 
$Errno 0;
    var 
$Error "";

    var 
$type "mysql";
    var 
$revision "1.2";

    var 
$Link_ID 0;
    var 
$Query_ID 0;

    function 
DB_Sql($query "")
    {
        
$this->query($query);
    } 

    function 
link_id()
    {
        return 
$this->Link_ID;
    } 

    function 
query_id()
    {
        return 
$this->Query_ID;
    } 

    function 
connect($Database ""$Host ""$User ""$Password "")
    {

        if (
"" == $Database)
            
$Database $this->Database;
        if (
"" == $Host)
            
$Host $this->Host;
        if (
"" == $User)
            
$User $this->User;
        if (
"" == $Password)
            
$Password $this->Password;

        if (
== $this->Link_ID) {
            
$this->Link_ID mysql_pconnect($Host$User$Password);
            if (!
$this->Link_ID) {
                
$this->halt("pconnect($Host, $User, $Password) failed.");
                return 
0;
            } 

            if (!@
mysql_select_db($Database$this->Link_ID)) {
                
$this->halt("cannot use database " $this->Database);
                return 
0;
            } 
        } 

        return 
$this->Link_ID;
    } 

    function 
free()
    {
        @
mysql_free_result($this->Query_ID);
        
$this->Query_ID 0;
    } 

    function 
query($Query_String)
    {

        if (
$Query_String == "")

            return 
0;

        if (!
$this->connect()) {
            return 
0;

        } ;
        if (
$this->Query_ID) {
            
$this->free();
        } 

        if (
$this->Debug)
            
printf("Debug: query = %s<br>n"$Query_String);

        
$this->Query_ID = @mysql_query($Query_String$this->Link_ID);
        
$this->Row 0;
        
$this->Errno mysql_errno();
        if (!
$this->Query_ID) {
            
$this->halt("Invalid SQL: " $Query_String);
        } 
        return 
$this->Query_ID;
    } 

    function 
result()
    {
        if (!
$this->Query_ID) {
            
$this->halt("result called with no query pending.");
            return 
0;
        } 

        
$this->Record = @mysql_fetch_array($this->Query_ID);
        
$this->Row += 1;
        
$this->Errno mysql_errno();
        
$this->Error mysql_error();

        
$stat is_array($this->Record);
        if (!
$stat && $this->Auto_Free) {
            
$this->free();
        } 
        return 
$stat;
    } 

    function 
seek($pos 0)
    {
        
$status = @mysql_data_seek($this->Query_ID$pos);
        if (
$status)
            
$this->Row $pos;
        else {
            
$this->halt("seek($pos) failed: result has " $this->num_rows() . " rows");

            @
mysql_data_seek($this->Query_ID$this->num_rows());
            
$this->Row $this->num_rows;
            return 
0;
        } 

        return 
1;
    } 

    function 
lock($table$mode "write")
    {
        
$this->connect();

        
$query "lock tables ";
        if (
is_array($table)) {
            while (list(
$key$value) = each($table)) {
                if (
$key == "read" && $key != 0) {
                    
$query .= "$value read, ";
                } else {
                    
$query .= "$value $mode, ";
                } 
            } 
            
$query substr($query0, -2);
        } else {
            
$query .= "$table $mode";
        } 
        
$res = @mysql_query($query$this->Link_ID);
        if (!
$res) {
            
$this->halt("lock($table, $mode) failed.");
            return 
0;
        } 
        return 
$res;
    } 

    function 
unlock()
    {
        
$this->connect();

        
$res = @mysql_query("unlock tables");
        if (!
$res) {
            
$this->halt("unlock() failed.");
            return 
0;
        } 
        return 
$res;
    } 

    function 
affected_rows()
    {
        return @
mysql_affected_rows($this->Link_ID);
    } 

    function 
num_rows()
    {
        return @
mysql_num_rows($this->Query_ID);
    } 

    function 
num_fields()
    {
        return @
mysql_num_fields($this->Query_ID);
    } 

    function 
nf()
    {
        return 
$this->num_rows();
    } 

    function 
np()
    {
        print 
$this->num_rows();
    } 

    function 
f($Name)
    {
        return 
$this->Record[$Name];
    } 

    function 
p($Name)
    {
        print 
$this->Record[$Name];
    } 

    function 
nextid($seq_name)
    {
        
$this->connect();

        if (
$this->lock($this->Seq_Table)) {

            
$q sprintf("select nextid from %s where seq_name = '%s'",
                
$this->Seq_Table,
                
$seq_name);
            
$id = @mysql_query($q$this->Link_ID);
            
$res = @mysql_fetch_array($id);

            if (!
is_array($res)) {
                
$currentid 0;
                
$q sprintf("insert into %s values('%s', %s)",
                    
$this->Seq_Table,
                    
$seq_name,
                    
$currentid);
                
$id = @mysql_query($q$this->Link_ID);
            } else {
                
$currentid $res["nextid"];
            } 
            
$nextid $currentid 1;
            
$q sprintf("update %s set nextid = '%s' where seq_name = '%s'",
                
$this->Seq_Table,
                
$nextid,
                
$seq_name);
            
$id = @mysql_query($q$this->Link_ID);
            
$this->unlock();
        } else {
            
$this->halt("cannot lock " $this->Seq_Table " - has it been created?");
            return 
0;
        } 
        return 
$nextid;
    } 

    function 
metadata($table ''$full false)
    {
        
$count 0;
        
$id 0;
        
$res = array();
        if (
$table) {
            
$this->connect();
            
$id = @mysql_list_fields($this->Database$table);
            if (!
$id)
                
$this->halt("Metadata query failed.");
        } else {
            
$id $this->Query_ID;
            if (!
$id)
                
$this->halt("No query specified.");
        } 

        
$count = @mysql_num_fields($id);
        if (!
$full) {
            for (
$i 0$i $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 $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;
            } 
        } 
        if (
$table) @mysql_free_result($id);
        return 
$res;
    } 

    function 
halt($msg)
    {
        
$this->Error = @mysql_error($this->Link_ID);
        
$this->Errno = @mysql_errno($this->Link_ID);
        if (
$this->Halt_On_Error == "no")
            return;

        
$this->haltmsg($msg);

        if (
$this->Halt_On_Error != "report")
            die(
"Session halted.");
    } 

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

    function 
table_names()
    {
        
$this->query("SHOW TABLES");
        
$i 0;
        while (
$info mysql_fetch_row($this->Query_ID)) {
            
$return[$i]["table_name"] = $info[0];
            
$return[$i]["tablespace_name"] = $this->Database;
            
$return[$i]["database"] = $this->Database;
            
$i++;
        } 
        return 
$return;
    } 

    function 
getResArray()
    {
        return @
mysql_fetch_array($this->Query_ID);
    }

    function 
getResTotal(){
        return @
mysql_num_rows($this->Query_ID);
    }
    
    
/*****************无魂扩展部分***************/
    
    /*
        *方法    setTable
        *功能    设定查询表名
        *参数    $t        表名
        *返回    无
    */
    
function setTable($t){
        
$this->table=$f;
    }
//end fun setTable


    /*
        *方法    getField
        *功能    取得要查询的记录
        *参数    $f            记录数组
        *返回    string
    */
    
function getField($f=array()){
        
$this->field=$f;
        if(empty(
$f)){
            
$this->errMes[]="记录不为空";
            
$this->mes();
        }
        foreach(
$f as $v){
            
$field.=$v.",";
        }
        
$field=substr($field,0,-1);
        return 
$field;
    }
//end fun getField

    /*
        *方法    setFiled
        *功能    设定字段
        *参数    $f        字段
        *返回    无
    */
    
function setField($f=array()){
        
$this->field=$f;
    }
//end fun setFiled

    /*
        *方法    getRes
        *功能    得到用户记录
        *参数    $f        字段
        *返回    无
    */
    
function getRes($sql){
        
$this->query($sql);
        while(
$this->result()){
            foreach(
$this->field as $v){
                
$res[$v][]=$this->f($v);
            }
        }
        return 
$res;
    }
//end fun getRes
    

    /*
        *方法    getAmount
        *功能    得到数量
        *参数    $t        表名
                $w        条件
        *返回    ini
    */
    
function getAmount($t,$w=''){
        
$sql="select count(*) as tot from $t ";
        if(!empty(
$w))$sql.=$w;
        
//echo $sql;
        
$this->query($sql);
        
$this->result();
        
$tot=$this->f("tot");
        return 
$tot;
    }
//end fun getAmount

    /*
        *方法    mes
        *功能    显示错误信息
        *参数    无
        *返回    无
    */
    
function mes(){
        if(
count($this->errMes)!=0){
            foreach(
$this->errMes as $v){
                echo 
'<FONT SIZE="" COLOR="#FF0000">[无魂报告]:</FONT>'.$v."<br>";
            }
            echo 
BACK;
            exit;
        }else{
            
//echo "^_^恭喜,操作成功!<br>";
        
}
    }
//end fun mes



    
function closeDb()
    {
        @
mysql_close($this->Link_ID);
    } 
}
//end class db_mysql.php

?>
然后配合我的Sql类进行得到sql语句..这里我就写了sel部分...

<?php
//****************Sql类*******************
//***************************************
//****                                 ****
//****        作者:    无魂                 ****
//****        日期:    2004-3-26         ****
//****        版本:    1.0                 ****
//****        版权:    无魂                 ****
//****                                 ****
//***************************************
//***************************************
require_once("Base.class.php");
/*
    *类名    Sql
    *功能    Sql类
    *版本    1.0
    *日期    2004-3-26
    *作者    无魂
    *版权    无魂
    *说明    无
*/
class Sql extends Base{

    var 
$table;                                        //表
    
var $where            ='';                        //条件
    
var $order            ='';                        //排序
    
var $limit;                                        //查询范围
    
    /*
        *方法    getSql
        *功能    取得Sql语句
        *参数    $field            字段值
        *返回    string
    */
    
function getSel($field){
        if(empty(
$field)){
            
$this->errMes[]="参数不能为空";
            
parent::mes();
        }
        
$sql="select ".$field." from ".$this->table." ".$this->where." ".$this->order." ".$this->limit;
        return 
$sql;
    }
//end fun getSel

    /*
        *方法    getDel
        *功能    取得删除语句
        *参数    $field            字段值
        *返回    array
    */
    
function getDel($field){
        if(empty(
$field)){
            
$this->errMes[]="参数不能为空";
            
parent::mes();
        }
        
$sql="select ".$field." from ".$this->table." ".$this->where." ".$this->order;
        return 
$sql;
    }
//end fun getDel


    
    /* ======>set部分<======= */

    /*
        *方法    setTable
        *功能    设定表
        *参数    $t            表名
        *返回    无
    */
    
function setTable($t){
        
$this->table=$t;
    }
//end fun setTable

    /*
        *方法    setWhere
        *功能    设定条件
        *参数    $w            条件
        *返回    无
    */
    
function setWhere($w){
        
$this->where=$w;
    }
//end fun setWhere

    /*
        *方法    setOrder
        *功能    设定排序
        *参数    $o            排序
        *返回    无
    */
    
function setOrder($o){
        
$this->order=$o;
    }
//end fun setOrder

    /*
        *方法    setLimit
        *功能    设定排序
        *参数    $o            排序
        *返回    无
    */
    
function setLimit($m,$f=0){
        
$this->limit="limit $f,$m";
    }
//end fun setLimit


}//end class Sql

?>
下面是Sql类用到的base类...进行错误报告和一下基本常用的功能的.....(可以不用base然后把 "class Sql extends Base{" 中的extends Base去掉..

base类:Base.class.php

<?php
//****************基础类*******************
//***************************************
//****                                 ****
//****        作者:    无魂                 ****
//****        日期:    2004-3-26         ****
//****        版本:    1.0                 ****
//****        版权:    无魂                 ****
//****                                 ****
//***************************************
//***************************************

/*
    *类名    Base
    *功能    基础类
    *版本    1.0
    *日期    2004-3-26
    *作者    无魂
    *版权    无魂
    *说明    无
*/
class Base {
    var 
$errMes                =array();                    //记录消息
    
    /*
        *方法    substrGb
        *功能    中文截取
        *参数    $str        要截取字符串
                $start        从什么地方开始
                $len        到什么地方
        *返回    string
    */
    
function substrGb($str,$start,$len){ 
        for(
$i=0;$i<$start+$len;$i++){ 
            
$tmpstr=(ord($str[$i])>=161 && ord($str[$i])<=247&& ord($str[$i+1])>=161 && ord($str[$i+1])<=254)?$str[$i].$str[++$i]:$tmpstr=$str[$i]; 
            if (
$i>=$start&&$i<($start+$len))$tmp .=$tmpstr
        } 
        return 
$tmp
    }
//end fun substrGb

    /*
        *方法    getImg
        *功能    上传图片并返回图片名称
        *参数    $path        物理路径
        *返回    string
        *说明    需要upload.php类
    */
    
function getImg($img,$path){
        if(!empty(
$img)){
            require_once(
"upload.class.php");
            foreach(
$img as $k=>$v){
                
$u=new phpUpload($v['tmp_name'],$v['name'],$path."upload/images/zixun/");
                
$u->rndFileName();
                
$u->size("1000");
                
$u->type("jpg,gif,jpeg,JPEG");
                
$res=$u->up();
                if(
$res[0]){
                    
$len=strlen($path)-1;
                    
$imgName=$u->getUsefulRf($len);
                    return 
$imgName;
                }
                else{
                    
$this->errMes[]= "图片".$v['name']."上传失败";
                    
$this->mes();
                }
            }
            unset(
$u);
        }
    }
//end fun getImg

    
function toHtml($str){
        
$str=str_replace("&lt;COLOR","<font color=",$str);
        
$str=str_replace("&lt;/COLOR&gt;","</font>",$str);
        
$str=str_replace("&lt;img&gt;","<img src='",$str);
        
$str=str_replace("&lt;/img&gt;","'>",$str);

        
$str=str_replace("&lt;","<",$str);
        
$str=str_replace("&gt;",">",$str);
        return 
$str;
    }


    
/*
        *方法    mes
        *功能    显示错误信息
        *参数    无
        *返回    无
    */
    
function mes(){
        if(
count($this->errMes)!=0){
            foreach(
$this->errMes as $v){
                echo 
'<FONT SIZE="" COLOR="#FF0000">[无魂报告]:</FONT>'.$v."<br>";
            }
            echo 
'<a href="javascript:history.go(-1)"><font     color="#FF0000">[返 回]</font> </a>';
            exit;
        }else{
            
//echo "^_^恭喜,操作成功!<br>";
        
}
    }
//end fun mes

}

?>
********************************使用说明*****************************
例子:

<?php
require_once("db_mysql.php");//引入类
require_once("sql.class.php");

$db=new mysql($host,$u,$p,$datebase)//连接数据库

$sql=new Sql;//生成sql对象

//
//方法的参数部分的说明在类里有写..可以到那里去看...
//
$sql->setTable(TB_ZX);//设定要查询的表
$sql->setOrder("order by shijian desc");//查询顺序
$sql->setLimit(5);//查询访问
$sql->setWhere($w);//查询条件
$field=$db->getField(array("id","title","article"));//查询字段
$sel=$sql->getSel($field);//得到sql语句
$res=$db->getRes($sel);//得到结果以2维数组的形式存在.
//$res[id][0]代表第一个查到的id
//$res[title][1]代表第二个查到的title
//依次类对.....

/*************不使用sql类*****************/

//如果不使用sql类应该这样写
$sql="select * from table where .....";
$db->getField(array("id","title","article"));//查询字段
$res=$db->