php 数据查询与连接类

class MySQL {var $link;var $result;var $querys;function MySQL($host =
”, $user = ”, $pw = ”, $db = ”, $encode = ‘UTF8’) {$this-querys =
0;if($host != ” $user != ” $db != ”)
{$this-connect($host,$user,$pw,$db,$encode);}}/** * connect to
database * * @param unknown_type $host * @param unknown_type $user
* @param unknown_type $pw * @param unknown_type $db * @return
boolean */function connect($host,$user,$pw,$db,$encode = ‘UTF8’)
{$resource = mysql_connect($host,$user,$pw);if(is_resource($resource))
{$this-link = $resource;if(mysql_select_db($db,$this-link))
{unset($resource);if (floatval(mysql_get_server_info($this-link)) 4.1
isset($encode)) {mysql_query(‘SET NAMES ‘.$encode.”);}return true;}
else {unset($resource);return false;}} else {unset($resource);return
false;}}/** * query sql * * @param unknown_type $query * @return
unknown */function query($query) {$result =
mysql_query($query,$this-link);$this-querys ++;if($result)
{$this-result = $result;return true;} else {return false;}}/** *
fetch a row * * @return mixed */function fetch()
{if(is_resource($this-result)) {return
mysql_fetch_array($this-result);} else {return false;}}/** * fetch
all result * * @return mixed */function fetchAll()
{if(is_resource($this-result)) {$temp = array();while ($row =
mysql_fetch_array($this-result)) {$temp[] = $row;}return $temp;}
else {return false;}}/** * return the querys * * @return integer
*/function getQuerys() {return $this-querys;}/** * get the numbers
of the result * * @return int */function getNumberRow() {if
(is_resource($this-result)) {return mysql_num_rows($this-result);}
else {return 0;}}/** * free result * * @return boolean */function
free() {if(is_resource($this-result))
{mysql_free_result($this-result);return true;} else {return
false;}}/** * close mysql connect * * @return boolean */function
close() {if(is_resource($this-link)) {mysql_close($this-link);return
true;} else {return false;}}}

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

?php/*** Class program for yinghua05-2* designer :songsong*/

  var $debug=false;

php 数据查询与连接类

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

?

<?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{

   /**
    * 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();
   }

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

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

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

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

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

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

    代码如下:

   /**
    * 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);
   }

  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);
  }
}
?>

   /**
    * evaluate the result (size, width)
    *
    * @return num
    */
   function affected_rows()
   {
       return @mysql_affected_rows($this->link_id);
   }

  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();
  }

   /**
    * 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;
   }

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

<?
class module{

  var $tbname;

  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’];
  }

前端一直使用PHP5,的确使用起来特别的爽,现在为了能在俺的虚拟主机上跑,不得不改成PHP4的。这几个库类我以前发在PHPCHIAN,地址是

   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());
   }

  var $mysql;

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

   
   /**
    * 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;
   }

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

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

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

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

   function insert_id()
   {
       return @mysql_insert_id($this->link_id);
   }

  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 num_rows()
   {
       return @mysql_num_rows($this->query_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;
   }

发表评论

电子邮件地址不会被公开。 必填项已用*标注