支持php4、php5的mysql数据库操作类


Posted in PHP onJanuary 10, 2008

前端一直使用PHP5,的确使用起来特别的爽,现在为了能在俺的虚拟主机上跑,不得不改成PHP4的。这几个库类我以前发在PHPCHIAN,地址是http://www.phpchina.com/bbs/viewthread.php?tid=5687&highlight=。(前几天在网上搜索了下,发现很多转载我的这几篇文章都没有说明出处,而且把我的版权都删除了,气晕了。)

    昨天改写了数据库操作类,恰好在我简化zend Framework也能用到。

    代码如下:

<?php
/**
* filename: DB_Mysql.class.php
* @package:phpbean
* @author :feifengxlq<[email]feifengxlq@gmail.com[/email]>
* @copyright :Copyright 2006 feifengxlq
* @license:version 1.2
* create:2006-5-30
* modify:2006-10-19 by feifengxlq
* description:the interface of mysql.

* example:
* ////////////Select action (First mode)//////////////////////////////
$mysql=new DB_Mysql("localhost","root","root","root");    
$rs=$mysql->query("select * from test");
for($i=0;$i<$mysql->num_rows($rs);$i++)
    $record[$i]=$mysql->seek($i);
print_r($record);
$mysql->close();
* ////////////Select action (Second mode)//////////////////////////////
 $mysql=new DB_Mysql("localhost","root","root","root");
 $rs=$mysql->execute("select * from test");
 print_r($rs);
 $mysql->close();
* /////////////insert action////////////////////////////
   $mysql=new DB_Mysql("localhost","root","root","root");    
   $mysql->query("insert into test(username) values('test from my DB_mysql')");
   printf("%s",$mysql->insert_id());
   $mysql->close();
*/
class mysql{

   /* private: connection parameters */
   var $host="localhost";
   var $database="";
   var $user="root";
   var $password="";

   /* private: configuration parameters */
   var $pconnect=false;
   var $debug=false;

   /* private: result array and current row number */
   var $link_id=0;
   var $query_id=0;
   var $record=array();

   /**
    * construct 
    *
    * @param string $host
    * @param string $user
    * @param string $password
    * @param string $database
    */
   function __construct($host="localhost",$user="root",$password="",$database="")
   {
       $this->set("host",$host);
       $this->set("user",$user);
       $this->set("password",$password);
       $this->set("database",$database);
       $this->connect();
   }

   /**
    * set the value for the param of this class
    *
    * @param string $var
    * @param string $value
    */
   function set($var,$value)
   {
       $this->$var=$value;
   }

   
   /**
    * connect to a mysql server,and choose the database.
    *
    * @param string $database
    * @param string $host
    * @param string $user
    * @param string $password
    * @return link_id
    */
   function connect($database="",$host="",$user="",$password="")
   {
       if(!empty($database))$this->set("database",$database);
       if(!empty($host))$this->set("host",$host);
       if(!empty($user))$this->set("user",$user);
       if(!empty($password))$this->set("password",$password);
       if($this->link_id==0)
       {
           if($this->pconnect)
              $this->link_id=@mysql_pconnect($this->host,$this->user,$this->password);
           else 
              $this->link_id=@mysql_connect($this->host,$this->user,$this->password);
           if(!$this->link_id)
              die("Mysql Connect Error in ".__FUNCTION__."():".mysql_errno().":".mysql_error());
           if(!@mysql_select_db($this->database,$this->link_id))
              die("Mysql Select database Error in ".__FUNCTION__."():".mysql_errno().":".mysql_error());
       }
       return $this->link_id;
   }

   /**
    * query a sql into the database
    *
    * @param string $strsql
    * @return query_id
    */
   function query($strsql="")
   {
       if(empty($strsql)) die("Mysql Error:".__FUNCTION__."() strsql is empty!");
       if($this->link_id==0) $this->connect();
       if($this->debug) printf("Debug query sql:%s",$strsql);
       $this->query_id=@mysql_query($strsql,$this->link_id);
       if(!$this->query_id) die("Mysql query fail,Invalid sql:".$strsql.".");
       return $this->query_id;
   }

   /**
    * query a sql into the database,while it is differernt from the query() method,
    * this method will return a record(array);
    *
    * @param string $strsql
    * @param string $style
    * @return $record is a array()
    */
   function Execute($strsql,$style="array")
   {
       $this->query($strsql);
       if(!empty($this->record))$this->record=array();
       $i=0;
       if($style=="array"){
           while ($temp=@mysql_fetch_array($this->query_id)) {
               $this->record[$i]=$temp;
               $i++;
           }
       }else{
           while ($temp=@mysql_fetch_object($this->query_id)) {
               $this->record[$i]=$temp;
               $i++;
           }
       }            
       unset($i);
       unset($temp);
       return $this->record;
   }

   /**
    * seek,but not equal to mysql_data_seek. this methord will return a list.
    *
    * @param int $pos
    * @param string $style
    * @return record
    */
   function seek($pos=0,$style="array")
   {
       if(!@mysql_data_seek($this->query_id,$pos))
           die("Error in".__FUNCTION__."():can not seek to row ".$pos."!");
       $result=@($style=="array")?mysql_fetch_array($this->query_id):mysql_fetch_object($this->query_id);
       if(!$result) die("Error in ".__FUNCTION__."():can not fetch data!");
       return $result;
   }
   /**
    * free the result of query
    *
    */
   function free()
   {
       if(($this->query_id)&($this->query_id!=0))@mysql_free_result($this->query_id);
   }

   /**
    * evaluate the result (size, width)
    *
    * @return num
    */
   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 insert_id()
   {
       return @mysql_insert_id($this->link_id);
   }

   function close()
   {
       $this->free();
       if($this->link_id!=0)@mysql_close($this->link_id);
       if(mysql_errno()!=0) die("Mysql Error:".mysql_errno().":".mysql_error());
   }

   function select($strsql,$number,$offset)
   {
       if(empty($number)){
           return $this->Execute($strsql);
       }else{
           return $this->Execute($strsql.' limit '.$offset.','.$number);
       }
   }

   function __destruct()
   {
       $this->close();
       $this->set("user","");
       $this->set("host","");
       $this->set("password","");
       $this->set("database","");
   }
}
?> 

在此基础上,我顺便封装SIDU(select,insert,update,delete)四种基本操作,作为简化的zend Framework的module。代码如下(这个没写注释了,懒的写。。):

<?
class module{

  var $mysql;

  var $tbname;

  var $debug=false;

  function __construct($tbname){
     if(!is_string($tbname))die('Module need a args of tablename');
   $this->tbname=$tbname;
   $this->mysql=phpbean::registry('db');
  }

  function _setDebug($debug=true){
     $this->debug=$debug;
  }

  function add($row){
     if(!is_array($row))die('module error:row should be an array');
   $strsql='insert into `'.$this->tbname.'`';
   $keys='';
   $values='';
   foreach($row as $key=>$value){
      $keys.='`'.$key.'`,';
    $values.='\''.$value.'\'';
   }
   $keys=rtrim($keys,',');
   $values=rtrim($values,',');
   $strsql.=' ('.$keys.') values ('.$values.')';
   if($this->debug)echo '<hr>'.$strsql.'<hr>';
   $this->mysql->query($strsql);
   return $this->mysql->insert_id();
  }

  function query($strsql){
     return $this->mysql->Execute($strsql);
  }

  function count($where=''){
     $strsql='select count(*) as num from `'.$this->tbname.'` ';
   if(!empty($where))$strsql.=$where;
   $rs=$this->mysql->Execute($strsql);
   return $rs[0]['num'];
  }

  function select($where=''){
     $strsql='select * from `'.$this->tbname.'` ';
   if(!empty($where))$strsql.=$where;
   return $this->mysql->Execute($strsql);
  }

  function delete($where=''){
     if(empty($where))die('Error:the delete method need a condition!');
   return $this->mysql->query('delete from `'.$this->tbname.'` '.$where);
  }

  function update($set,$where){
     if(empty($where))die('Error:the update method need a condition!');
   if(!is_array($set))die('Error:Set must be an array!');
   $strsql='update `'.$this->tbname.'` ';
   //get a string of set
   $strsql.='set ';
   foreach($set as $key=>$value){
      $strsql.='`'.$key.'`=\''.$value.'\',';
   }
   $strsql=rtrim($strsql,',');
   return $this->mysql->query($strsql.' '.$where);
  }

  function detail($where){
     if(empty($where))die('Error:where should not empty!');
   $rs=$this->mysql->query('select * from `'.$this->tbname.'` '.$where);
   return $this->mysql->seek(0);
  }
}
?>

PHP 相关文章推荐
PHP4在Windows2000下的安装
Oct 09 PHP
用 PHP5 轻松解析 XML
Dec 04 PHP
弄了个检测传输的参数是否为数字的Function
Dec 06 PHP
关于Intype一些小问题的解决办法
Mar 28 PHP
PHP源码之 ext/mysql扩展部分
Jul 17 PHP
php 静态页面中显示动态内容
Aug 14 PHP
php下封装较好的数字分页方法
Nov 23 PHP
php的curl封装类用法实例
Nov 07 PHP
PHP XML和数组互相转换详解
Oct 26 PHP
PHP中list方法用法示例
Dec 01 PHP
PHP+Ajax 检测网络是否正常实例详解
Dec 16 PHP
详解Laravel设置多态关系模型别名的方式
Oct 17 PHP
让PHP支持页面回退的两种方法
Jan 10 #PHP
php下使用SMTP发邮件的代码
Jan 10 #PHP
ZF等常用php框架中存在的问题
Jan 10 #PHP
逐步提升php框架的性能
Jan 10 #PHP
在PHP中使用Sockets 从Usenet中获取文件
Jan 10 #PHP
php扩展ZF――Validate扩展
Jan 10 #PHP
set_include_path在win和linux下的区别
Jan 10 #PHP
You might like
让的PHP代码飞起来的40条小技巧(提升php效率)
2010/04/12 PHP
使用PHP生成二维码的两种方法(带logo图像)
2014/03/14 PHP
php在apache环境下实现gzip配置方法
2015/04/02 PHP
php中array_slice和array_splice函数解析
2016/10/18 PHP
PHP微信开发之微信录音临时转永久存储
2018/01/26 PHP
兼容ie、firefox的图片自动缩放的css跟js代码分享
2013/08/12 Javascript
js左侧三级菜单导航实例代码
2013/09/13 Javascript
网页下载文件期间如何防止用户对网页进行其他操作
2014/06/27 Javascript
JavaScript和CSS交互的方法汇总
2014/12/02 Javascript
javascript中数组和字符串的方法对比
2016/07/20 Javascript
Angular中使用ui router实现系统权限控制及开发遇到问题
2016/09/23 Javascript
ros::spin() 和 ros::spinOnce()函数的区别及详解
2016/10/01 Javascript
基于pako.js实现gzip的压缩和解压功能示例
2017/06/13 Javascript
详解Vue.js项目API、Router配置拆分实践
2018/03/16 Javascript
Vue 实现创建全局组件,并且使用Vue.use() 载入方式
2020/08/11 Javascript
[01:00]选手抵达华西村 整装待发备战2016国际邀请赛中国区预选赛
2016/06/25 DOTA
[01:59]深扒TI7聊天轮盘语音出处 1
2017/05/11 DOTA
python学习手册中的python多态示例代码
2014/01/21 Python
python多线程方式执行多个bat代码
2016/06/07 Python
python使用epoll实现服务端的方法
2018/10/16 Python
Linux下Python安装完成后使用pip命令的详细教程
2018/11/22 Python
Python 隐藏输入密码时屏幕回显的实例
2019/02/19 Python
基于Python打造账号共享浏览器功能
2019/05/30 Python
python实现文件批量编码转换及注意事项
2019/10/14 Python
你应该知道的Python3.6、3.7、3.8新特性小结
2020/05/12 Python
用纯css3实现的图片放大镜特效效果非常不错
2014/09/02 HTML / CSS
通过CSS3的object-fit来调整图片适配尺寸的技巧简介
2016/02/27 HTML / CSS
大学新生军训感言
2014/02/25 职场文书
乡镇办公室工作决心书
2014/03/11 职场文书
乡镇交通安全实施方案
2014/03/29 职场文书
化工工艺设计求职信
2014/06/25 职场文书
小城镇建设汇报材料
2014/08/16 职场文书
写给老师的感谢信
2015/01/20 职场文书
2016大学生暑期社会实践心得体会
2016/01/14 职场文书
如何用python反转图片,视频
2021/04/24 Python
python Tkinter模块使用方法详解
2022/04/07 Python