六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 23|回复: 0

一个PHP动态数据库基础类

[复制链接]

升级  59.33%

116

主题

116

主题

116

主题

举人

Rank: 3Rank: 3

积分
378
 楼主| 发表于 2013-1-28 19:44:55 | 显示全部楼层 |阅读模式
参考:http://www.ibm.com/developerworks/cn/opensource/os-php-flexobj/

需要PHP5支持才行,使用了__call __get __set等动态方法
class DBObject{  private $id = 0;  private $table;  private $fields = array();  function __construct( $table, $fields )  {    $this->table = $table; //数据表名    foreach( $fields as $key )      $this->fields[ $key ] = null; //数据字段  }function __get( $key )   //可读字段  {    return $this->fields[ $key ];  }  function __set( $key, $value ) //可写字段  {    if ( array_key_exists( $key, $this->fields ) )    {                                //添加条件可以限制某些字段不能写      $this->fields[ $key ] = $value;      return true;    }    return false;  }  function load( $id )  {    global $db;  //数据库对象    $res = $db->query(  "SELECT * FROM ".$this->table." WHERE ".  $this->table."_id=?",      array( $id )    );    $res->fetchInto( $row, DB_FETCHMODE_ASSOC );    $this->id = $id;    foreach( array_keys( $row ) as $key )      $this->fields[ $key ] = $row[ $key ];  }  function insert()  {    global $db;    $fields = $this->table."_id, ";    $fields .= join( ", ", array_keys( $this->fields ) );    $inspoints = array( "0" );    foreach( array_keys( $this->fields ) as $field )      $inspoints []= "?";    $inspt = join( ", ", $inspoints );$sql = "INSERT INTO ".$this->table." ( $fields )   VALUES ( $inspt )";    $values = array();    foreach( array_keys( $this->fields ) as $field )      $values []= $this->fields[ $field ];    $sth = $db->prepare( $sql );    $db->execute( $sth, $values );    $res = $db->query( "SELECT last_insert_id()" );    $res->fetchInto( $row );    $this->id = $row[0];    return $row[0];  }  function update()  {    global $db;    $sets = array();    $values = array();    foreach( array_keys( $this->fields ) as $field )    {      $sets []= $field.'=?';      $values []= $this->fields[ $field ];    }    $set = join( ", ", $sets );    $values []= $this->id;$sql = 'UPDATE '.$this->table.' SET '.$set.  ' WHERE '.$this->table.'_id=?';    $sth = $db->prepare( $sql );    $db->execute( $sth, $values );  }  function delete()  {    global $db;    $sth = $db->prepare(   'DELETE FROM '.$this->table.' WHERE '.   $this->table.'_id=?'    );    $db->execute( $sth,      array( $this->id ) );  }  function delete_all()  {    global $db;    $sth = $db->prepare( 'DELETE FROM '.$this->table );    $db->execute( $sth );  }}
继承时覆盖_construct 方法
function __construct()  {  parent::__construct( 'book',    array( 'author', 'title', 'publisher' ) );  }
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表