来源:http://trac.seagullproject.org/wiki/Howto/DB/CodeExamples/Simple

DB

初始化一个连接

只是在个别情况下你才需要初始化一个数据库连接。$this→dbh 在你的Manager的构造函数中执行完parent::SGL_Manager();时就已经自动初始化并可以使用了。

  $locator = &SGL_ServiceLocator::singleton();
  $dbh = $locator->get('DB');
  if (!$dbh) {
      $dbh = & SGL_DB::singleton();
      $locator->register('DB', $dbh);
  }

直接数据库查询

使用PEAR::DB进行数据库查询:

  $query = "
      SELECT  id, gid
      FROM " . $conf['table']['user'] . "
      WHERE   username = " . $dbh->quote($input->username) . "
      AND     passwd = '" . md5($input->password) . "'
      AND     is_acct_active = 1
      AND     gid <> " . SGL_UNASSIGNED;
  $aResult = $dbh->getRow($query, DB_FETCHMODE_ASSOC);

预备查询

使用PEAR::DB

  $sth = $dbh->prepare("  
      UPDATE " . $conf['table']['user'] . "
      SET gid = $gid
      WHERE id = ?");
  foreach ($aUsers as $uid => $username) {
      if ($uid == SGL_ADMIN) {
          continue;
      }
      $dbh->execute($sth, $uid);
  }

添加一个用户对象

添加一个带有15个以上永久存储属性的DataObject对象,注意使用的配置变量,使用本地时间值,启用sequence以保证数据库独立性。

  $oUser = DB_DataObject::factory($this->conf['table']['user']);
  $oUser->setFrom($input->user);
  $oUser->passwd = md5($input->user->passwd);
  if ($conf['registermgr']['autoEnable']) {
      $oUser->is_acct_active = 1;
  }
  $dbh = $oUser->getDatabaseConnection();
  $oUser->id = $dbh->nextId('usr');
  $oUser->date_created = $oUser->last_updated = SGL::getTime();
  $success = $oUser->insert();
 
howto/db/codeexamples/simple.txt · 最后更改: 2010/05/30 00:21 (外部编辑)
 
Except where otherwise noted, content on this wiki is licensed under the following license:GNU Free Documentation License 1.2