将PHP与Firebird或Interbase一起使用时的最佳做法

时间:2016-07-13 05:48:25

标签: php transactions connection firebird

php-interbase的文档很好 - 但不完整。特别是,没有与Firebird合作的完整示例。那你怎么做呢?

2 个答案:

答案 0 :(得分:2)

基本准则。

  1. 在ibase_connect()与ibase_pconnect()之间进行选择 - 连接活动的时间越短,冲突越少,维护越容易;可以执行备份。除非在处理时间(您正在执行大量实时读/写)方面连接到数据库“昂贵”,否则请根据需要使用ibase_connect()。
  2. 始终使用显式交易。总是。这很简单 - 假设每次调用ibase_prepare()或ibase_query()都需要一个事务句柄 - 从不是“原始”连接句柄。
  3. 始终根据需要使用ibase_commit()或ibase_rollback()进行交易。
  4. 读取操作的基本模板:

    // These would normally come from an include file...
    $db_path = '/var/lib/firebird/2.5/data/MyDatabase.fdb';
    $db_user = 'SYSDBA';
    $db_pass = 'masterkey';
    
    // use php error handling
    try {
        $dbh = ibase_connect( $db_path, $db_user, $db_pass );
        // Failure to connect 
        if ( !$dbh ) {
            throw new Exception( 'Failed to connect to database because: ' . ibase_errmsg(), ibase_errcode() );
        }
    
        $th = ibase_trans( $dbh, IBASE_READ+IBASE_COMMITTED+IBASE_REC_NO_VERSION);
        if ( !$th ) {
            throw new Exception( 'Unable to create new transaction because: ' . ibase_errmsg(), ibase_errcode() );
        }
    
        $qs = 'select FIELD1, FIELD2, from SOMETABLE order by FIELD1';
        $qh = ibase_query( $th, $qs );
    
        if ( !$qh ) {
            throw new Exception( 'Unable to process query because: ' . ibase_errmsg(), ibase_errcode() );
        }
    
        $rows = array();
        while ( $row = ibase_fetch_object( $qh ) ) {
            $rows[] = $row->NODE;
        }
    
        // $rows[] now holds results. If there were any.
    
        // Even though nothing was changed the transaction must be
        // closed. Commit vs Rollback - question of style, but Commit
        // is encouraged. And there shouldn't <gasp>used the S word</gasp>
        // be an error for a read-only commit...
    
        if ( !ibase_commit( $th ) ) {
            throw new Exception( 'Unable to commit transaction because: ' . ibase_errmsg(), ibase_errcode() );
        }
    
        // Good form would dictate error traps for these next two...
        // ...but these are the least likely to break...
        // and my fingers are getting tired.
        // Release PHP memory for the result set, and formally
        // close the database connection.
        ibase_free_result( $qh );
        ibase_close( $dbh );
    } catch ( Exception $e ) {
        echo "Caught exception: $e\n";
    }
    
    // do whatever you need to do with rows[] here...
    

答案 1 :(得分:0)

我14年前写的这篇文章也很有用:

http://www.phpbuilder.com/columns/glodt20020212.php3