登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Perfect-World

以無法為有法,以無限為有限!

 
 
 

日志

 
 

PHP中使用类对数据库进行操作  

2009-09-09 10:41:54|  分类: PHP |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
  在PHP编程过程中,对数据库的操作通常都是使用相应的函数,需要记忆一大套的函数和参数,针对不同的数据库还要使用不同的函数,如果要改变数据库系统,则要修改几乎所有的程序,浪费很多时间。有什么好的方法,可以使不用记忆操作每种数据库的各种函数,并且能够很容易的改变数据库系统?PHP的一个特点就是支持OOP(面向对象编程),我们可以把操作数据库的操作封装在一个类(Class)里,使用类的方法来操作数据库,如果要改变数据库我们只要重新定义这个类就行了。

  我们不需要自己定义相关的类,可以使用PHPLIB里已经定义的类来操作数据库。PHPLIB(PHP Base Library,PHP基本库,主页:< A href="< A href="http://phpwizard.net)是PHP的扩展,它提供了很多类库,使得程序员能很容易地建立一个交互式Web站点,PHPLIB最基本的功能包括以下几个方面:(1)用户认证,(2)Session管理,(3)权限及更加方便的使用数据库。"" target="_NEW">http://phpwizard.net)是PHP的扩展,它提供了很多类库,使得程序员能很容易地建立一个交互式Web站点,PHPLIB最基本的功能包括以下几个方面:(1)用户认证,(2)Session管理,(3)权限及更加方便的使用数据库。"< /A> target="_NEW">< A href="http://phpwizard.net)是PHP的扩展,它提供了很多类库,使得程序员能很容易地建立一个交互式Web站点,PHPLIB最基本的功能包括以下几个方面:(1)用户认证,(2)Session管理,(3)权限及更加方便的使用数据库。< " target="_NEW">http://phpwizard.net)是PHP的扩展,它提供了很多类库,使得程序员能很容易地建立一个交互式Web站点,PHPLIB最基本的功能包括以下几个方面:(1)用户认证,(2)Session管理,(3)权限及更加方便的使用数据库。< < /A> /A>

  下面具体介绍一下PHPLIB中针对MySQL数据库的类及其使用方法。
  PHPLIB中对MySQL的类的定义在db_mysql.inc中,其源代码如下:
  < ?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 {
  
   /* 数据库连接参数,改成你要连接的数据库的地址,数据库名,用户名和密码 */
   var $Host = "";
   var $Database = "";
   var $User = "";
   var $Password = "";
  
   /* 配置参数 */
   var $Auto_Free = 0; ## 设为1则自动执行mysql_free_result()函数
   var $Debug = 0; ## 设为1则显示SQL语句
   var $Halt_On_Error = "yes"; ## 出错时,"yes" (显示信息,中止运行), "no" (忽略错误,继续运行), "report" (忽略错误,显示警告信息)
   var $Seq_Table = "db_sequence";
  
   /* 数据库查询结果,和当前的行数 */
   var $Record = array();
   var $Row;
  
   /* 当前的错误号和错误信息 */
   var $Errno = 0;
   var $Error = "";
  
   /* public: this is an api revision, not a CVS revision. */
   var $type = "mysql";
   var $revision = "1.2";
  
   /* 联接句柄和执行SQL语句的句柄 */
   var $Link_ID = 0;
   var $Query_ID = 0;
  
  
  
   /* 以下是类的方法 */
   function DB_Sql($query = "") {
   $this->query($query);
   }
  
   /* 返回Link_ID和Query_ID值 */
   function link_id() {
   return $this->Link_ID;
   }
   function query_id() {
   return $this->Query_ID;
   }
  
   /* 连接处理 */
   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;
  
   /* 建立连接,选择数据库 */
   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 (Link_ID"<!@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) {
   /* 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;
   }
  
   /* 选择下一个查询记录 */
   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;
   }
  
   /* 定位到某一条查询记录 */
   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;
   }
  
   /* 锁定数据表 */
   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;
   }
  
  
   /* 计算查询的数量 */
   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];
   }
  
   /* 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;
   }
  
   /* 返回整个表的结果 */
   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;
   }
  
   /* 错误处理 */
   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;
   }
  }
  ?>
  
  我们用一个例子来解释DB_Sql类的使用方法:
  < ?
  01 require "db_mysql.inc";
  02 $db=new DB_Sql;
  03 $db->connect();
  04 $db->query("SELECT id, name FROM user");
  05 if ($db->nf())
  {
  06 while ($db->next_record())
  {
  07 echo "id=", $db->f("id");
  echo "< br>";
  echo "name";
  08 $db->p('name');
  echo "< br>";
  }
  09 $db->free();
  }
  ?>
  下面逐行进行解释:
  01- 包含db_mysql.inc
  02- 创建一个DB_Sql类的变量$db
  03- 调用DB_Sql类的connect方法,连接数据库
  04- 调用DB_Sql类的query方法,执行查询
  05- DB_Sql类的nf()方法返回查询后得到的记录条数
  06- next_record()方法把DB_Sql类的结果指针下移一条,如果到了结尾,就返回假值
  07- f()返回当前行某一个字段的值,参数是字段名
  08- p()相当于echo $db->f()
  09- 释放查询占用的内存

  几点注意:

  1、 要使用DB_Sql类,必须先创建一个DB_Sql类的对象
  2、 DB_Sql类的connect()方法实际上是调用PHP的mysql_pconnect()函数,该函数在程序结束时不会关闭mysql连接,所以比mysql_connect()函数效率要高,但要占用一定的系统资源。
  3、 最好把db_mysql.inc改成以php或php3结尾的文件名,以防被人查看到db_mysql.inc文件的内容,得知数据库的联接参数   
  评论这张
 
阅读(675)| 评论(0)

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018