在PHPLIB中的MYSQL类中加INSERT,UPDATE,DELETE等函数

<?php
/*
 * Session Management for PHP3
 *
 * Copyright (c) 1998-2000 NetUSE AG
 *                    Boris Erdmann, Kristian Koehntopp
 *
 * $Id: db_mysql.inc,v 1.2 2000/07/12 18:22:34 kk Exp $
 *
 */

class DB_Sql {
 
  /* public: connection parameters */
  var $Host     = "";
  var $Database = "";
  var $User     = "";
  var $Password = "";

  /* public: configuration parameters */
  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";

  /* 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. */
  var $type     = "mysql";
  var $revision = "1.2";

  /* private: link and query handles */
  var $Link_ID  = 0;
  var $Query_ID = 0;
 
  var $sql = "";

  /* public: constructor */
  function DB_Sql($query = "") {
      $this->query($query);
  }

  /* public: some trivial reporting */
  function link_id() {
    return $this->Link_ID;
  }

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

  /* public: connection management */
  function connect($Database = "", $Host = "", $User = "", $Password = "") {
    /* Handle defaults */
    if ("" == $Database)
      $Database = $this->Database;
    if ("" == $Host)
      $Host     = $this->Host;
    if ("" == $User)
      $User     = $this->User;
    if ("" == $Password)
      $Password = $this->Password;
     
    /* establish connection, select database */
    if ( 0 == $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;
  }

  /* public: discard the query result */
  function free() {
      @mysql_free_result($this->Query_ID);
      $this->Query_ID = 0;
  }

  /* public: perform a query */
  function query($Query_String) {
    /* No empty queries, please, since PHP4 chokes on them. */
    if ($Query_String == "")
      /* The empty query string is passed on from the constructor,
       * when calling the class without a query, e.g. in situations
       * like these: '$db = new DB_Sql_Subclass;'
       */
      return 0;

    if (!$this->connect()) {
      return 0; /* we already complained in connect() about that. */
    };

    # New query, discard previous result.
    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();
    $this->Error = mysql_error();
    if (!$this->Query_ID) {
      $this->halt("Invalid SQL: ".$Query_String);
    }

    # Will return nada if it fails. That's fine.
    return $this->Query_ID;
  }

  /* public: walk result set */
  function next_record() {
    if (!$this->Query_ID) {
      $this->halt("next_record 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;
  }
 
  /* public: insert record */
  function insert( $table, $data) {
    if ( is_array( $data ) ) {
  $this->sql = "INSERT INTO $table ( `".implode( "` , `" , array_keys($data) )."` )
    VALUES ( '".implode( "' , '", array_values($data) )."' )";
 } else {
  die("<strong>Error</strong> : Data Empty! ");
 }
 return $this->query( $this->sql );
  }
 
  /* public: delete record */
  function delete( $table, $where = "", $limit = 0 ) {
 $this->sql  = "DELETE FROM $table ";
 $this->sql .= $this->where($where);
 $this->sql .= intval($limit) ? " LIMIT ". intval($limit) : "";
 return $this->query( $this->sql );
  }
 
  /* public: update record */
  function update( $table, $update = "", $where = "", $limit = 0 ) {
    $setword = "";
 if( is_array( $update ) ) {
  while ( list( $field, $value ) = each($update) ) {
   $setword .= $setword ? " , " : "";
   $setword .= "`$field` = '".$value."'";
  }
 }else {
  $setword = $update;
 }
 
 $this->sql  = "UPDATE $table SET $setword ";
 $this->sql .= $this->where($where);
 $this->sql .= intval($limit) ? " LIMIT ". intval($limit) : "";
 return $this->query( $this->sql );
  }
 
 
  /* public: count record */
  function recordcount( $table, $where = "" ) {
    $this->sql = "SELECT COUNT(*) FROM $table " . $this->where($where);
 $this->query( $this->sql );
 if( $this->next_record() ) {
  return $this->f(0);
 }else {
  return 0;
 }
  }
 
  /* public: select record */
  function select( $table, $fields = "*", $where = "", $order = "", $group = "", $limit = 10 ) {
   
  }
 
  /* public: set where */
  function where( $where ) {
   $condition = "";
 if( is_array( $where ) ) {
  foreach( $where as $key => $val ){
   if( preg_match( "/^\d*$/", $key ) ) {//or
    foreach( $val as $k => $v ) {
     $condition .= $condition
         ? " OR ( `$k` = '".implode( "' AND `$k` = '", $v )."' )"
         : " WHERE ( `$k` = '".implode( "' AND `$k` = '", $v )."')";
    }
   }else {//and
    $condition .= $condition
        ? " AND ( `$key` = '".implode( "' OR `$key` = '", $val )."')"
        : " WHERE ( `$key` = '".implode( "' OR `$key` = '", $val )."')";
   }
  }
 }else {
  $condition .= " ".$where;
 }
    return $condition;
  }
 
  /* public: show sql */
  function showsql() {
    return $this->sql;
  }
 
  /* public: position in result set */
  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");

      /* half assed attempt to save the day,
       * but do not consider this documented or even
       * desireable behaviour.
       */
      @mysql_data_seek($this->Query_ID, $this->num_rows());
      $this->Row = $this->num_rows;
      return 0;
    }

    return 1;
  }

  /* public: table locking */
  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($query,0,-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;
  }

  /* public: evaluate the result (size, width) */
  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);
  }

  /* public: shorthand notation */
  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];
  }

  /* public: sequence numbers */
  function nextid($seq_name) {
    $this->connect();
   
    if ($this->lock($this->Seq_Table)) {
      /* get sequence number (locked) and increment */
      $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);
     
      /* No current value, make one */
      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;
  }

  /* public: return table metadata */
  function metadata($table='',$full=false) {
    $count = 0;
    $id    = 0;
    $res   = array();

    /*
     * Due to compatibility problems with Table we changed the behavior
     * of metadata();
     * depending on $full, metadata returns the following values:
     *
     * - full is false (default):
     * $result[]:
     *   [0]["table"]  table name
     *   [0]["name"]   field name
     *   [0]["type"]   field type
     *   [0]["len"]    field length
     *   [0]["flags"]  field flags
     *
     * - full is true
     * $result[]:
     *   ["num_fields"] number of metadata records
     *   [0]["table"]  table name
     *   [0]["name"]   field name
     *   [0]["type"]   field type
     *   [0]["len"]    field length
     *   [0]["flags"]  field flags
     *   ["meta"][field name]  index of field named "field name"
     *   The last one is used, if you have a field name, but no index.
     *   Test:  if (isset($result['meta']['myfield'])) { ...
     */

    // if no $table specified, assume that we are working with a query
    // result
    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);

    // made this IF due to performance (one if is faster than $count if's)
    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;
      }
    }
   
    // free the result only if we were called on a table
    if ($table) @mysql_free_result($id);
    return $res;
  }

  /* private: error handling */
  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;
  }
}
?>

时间: 2024-09-22 13:42:48

在PHPLIB中的MYSQL类中加INSERT,UPDATE,DELETE等函数的相关文章

如何在Java程序中访问mysql数据库中的数据并进行简单的操作_Mysql

在上篇文章给大家介绍了Myeclipse连接mysql数据库的方法,通过本文给大家介绍如何在Java程序中访问mysql数据库中的数据并进行简单的操作,具体详情请看下文. 创建一个javaProject,并输入如下java代码: package link; import java.sql.*; /** * 使用JDBC连接数据库MySQL的过程 * DataBase:fuck, table:person: * 使用myeclipse对mysql数据库进行增删改查的基本操作. */ public

java-Java中在同一个类中把一个方法中的数组元素传到另一个方法中,怎么传啊?麻烦大家说一下,谢谢了!

问题描述 Java中在同一个类中把一个方法中的数组元素传到另一个方法中,怎么传啊?麻烦大家说一下,谢谢了! Java中在同一个类中把一个方法中的数组元素传到另一个方法中,怎么传啊?麻烦大家说一下,谢谢了! 麻烦大家了 解决方案 直接作为参数传就是了 void f1() { int[] x = {1,2,3,4,5}; f2(x[1]); } void f2(int n) { } 解决方案二: Spring AOP代理机制以及方法调用在同一个类的另一个方法的问题 解决方案三: 可以使用全局变量的方

在MFC单文档程序中,如何在子对话框类中访问视类中的一个变量?

问题描述 在MFC单文档程序中,如何在子对话框类中访问视类中的一个变量? 如题,小弟最近遇到一个问题,新建一个单文档程序,并在其中引入对话框资源.我想在视类的OnDraw()函数中通过响应视类的一个变量的变化来改变视类窗口中图形的状态,而该视类变量的变化是由对话框中的一个控件控制的,这个控件是由旋钮控件和编辑控件捆绑而成的.在网上看了一些资料,试了其中的一些方法,都没能成功.论坛中高手众多,想请热心的高手们给个解决方法,在此先谢过了!能给个相似的例子的更好! 解决方案 要么你把那个变量定义成静态

c++-C++中 不能在类中访问this的地址

问题描述 C++中 不能在类中访问this的地址 如class a{ public: void show(){ cout<<&this; }}如果this是一个指针,为什么不能访问它的地址? 解决方案 首先要搞清楚this指针是存放在哪的?编译器在生成程序时加入了获取对象首地址的相关代码,并把获取的首地址存放在了寄存器ECX中(VC++编译器是放在ECX中,其它编译器有可能不同),也就是成员函数的其它参数正常都是存放在栈中,而this指针参数则是存放在寄存器中.寄存器不能像被外设寄存器

设置背景颜色-MFC中在View类中改变ClientDC的背景颜色

问题描述 MFC中在View类中改变ClientDC的背景颜色 我在MFC中建立了一个工程,用来在CView类中通过ClientDC来进行画图操作,现在想将ClientDC的默认背景颜色从白色改成黑色或者其他的颜色,求各位C大神指点,谢啦! PS:我试过在PreCreateWindow()和OnEraseBkgnd()函数中进行设置,但是没有成功,代码如下,请各位大神改正. BOOL CTestView::PreCreateWindow(CREATESTRUCT& cs) { cs.lpszCl

在C++中 怎么在派生类中使用基类中的成员变量 例如如下代码 怎样才能使其跑起来

问题描述 在C++中 怎么在派生类中使用基类中的成员变量 例如如下代码 怎样才能使其跑起来 #include using namespace std; class love{ public: char you() { int i=87, j=74 ,k=89; char a=char(i),b=char(j),c=char(k); return 0; } }; class Me:private love{ public: Me():l(a),u(b),n(c){} char const l,u,

Android中,BaseAdapter类中怎么获取屏幕宽度?

问题描述 Android中,BaseAdapter类中怎么获取屏幕宽度? 本人小白,自定义了个MyAdapter继承BaseAdapter,现在想在MyAdapter中获取屏幕宽度,但是该类不是Activity也不是service,WindowManeger获取不到.getSystemService(Context.WINDOW_SERVICE),Resources的getResources();也没有. 解决方案 如果 控件宽度是适应屏幕的话 getView(int position View

safari浏览器不支持silverlight 5中的LocalMessageReceiver类中的listen方法

问题描述 在macbooksafari浏览器上silverlight5.0中的LocalMessageReceiver类中[color=#FF0000]listen方法被阻塞,没有抛出异常.但就是代码运行到此处就不能进行下去了.在IE浏览器上正常 解决方案

属性-怎么在mvc3中动态给类中的property添加attribute?

问题描述 怎么在mvc3中动态给类中的property添加attribute? 有一个类A public class A{ public int Id{get;set;} public stirng Name{get;set;} } 通过反射将A中的property保存到txt文件中了,保存如下 Id.DisplayName=Id Name.DisplayName=Name 修改txt文件 Id.DisplayName=编号 Name.DisplayName=姓名 我想通过修改txt中的文件然后